Return value from overloaded method with Sinon

13 views Asked by At

I have the following example class, which has a overloaded method bar.

class Foo {
  bar(value: string): string;
  bar(value: number): number;
  bar(value: string | number): string | number {
    return value;
  }
}

In my tests I am normally creating an instance of foo and stubbing it.

const foo = new Foo();

const stub = Sinon.stub(foo, "bar");

When I stub the number part of the function, everything is still ok.

stub.withArgs(1).returns(2);

This above code is working without errors.

But this is not my use case. I want to stub the string part of my method like the following.

stub.withArgs("hello").returns("world");

When I do this, my IDE tells me the following:

For "hello":

Argument of type '"hello"' is not assignable to parameter of type 'number | SinonMatcher | undefined'.

For "world":

Argument of type 'string' is not assignable to parameter of type 'number'.

If I change the order of my overloaded methods, I would be successfully able to stub the string method, but not the number method. However, I can not change this order.

My question is: How can I stub the string part and not the number part of my method bar?

0

There are 0 answers