Given the following class:
class Foo {
public bar(): Bar;
public bar(string): Bar;
}
I want to stub only the first bar()
method, how should I do that or is there any workarounds?
Given the following class:
class Foo {
public bar(): Bar;
public bar(string): Bar;
}
I want to stub only the first bar()
method, how should I do that or is there any workarounds?
You can't do this. Typescript's overloaded methods don't exist at run time - they compile down to a single method.
From the typescript documentation:
TypeScript can only resolve a function call to a single overload
See this excellent answer to a different question for some discussion.
There's also this blog post which has the following example:
public getHero(name: string): Hero {
return /* some code here */
}
public getHero(name: string, skill: string): Hero {
return /* some other code here */
}
A breakpoint in the second function is hit when the first function is called, because Typescript has compiled away the two functions into one.
However if you need exactly this behaviour - you can make a complex stub that will allow you to call the underlying implementation in some cases using wrappedMethod
and callsFake
(documentation link here):
sinon
.stub(foo, "bar");
foo.bar.callsFake(function mockBar(maybeString?: string) {
if (string === undefined) { /* stub behaviour */}
else { return foo.bar.wrappedMethod(maybeString) }
});
As an aside, I would advise against complex stubbing, because now you are in a situation where it would be appropriate to write tests for your tests - in my view, it would be better to refactor the code so that this kind of stubbing is not necessary.