Search code examples
javascripttypescriptsinon

How to use sinon to replace the same method with two different return values?


A method that I am unit testing calls the same helper method with different parameters multiple times within the method. In order for me to test my method, I want to use sinon's replace function to replace the return value of this helper method with my mock data, but I need each time I call that helper method to return different mock data. How can I do this?

As an example:

const obj = {
  foo(num) {
    return 5 + num;
  },
  methodToTest() {
    return foo(1) + foo(2);
  },
};

I want to test whether methodToTest() will work properly if foo returns 6 when it is called with parameter value 1, and foo returns 7 when called with parameter value 2.

I guess what I'm looking for is a way to replace foo's return value depending on the parameter passed in, something like:

   sinon.replace(obj, 'foo(1)', sinon.fake.returns(6));
   sinon.replace(obj, 'foo(2)', sinon.fake.returns(7));

Any idea how I could do this? Would be very much appreciated.


Solution

  • Just create a fake foo function which provides multiple return values dynamicly based on argument.

    E.g.

    index.js:

    const obj = {
      foo(num) {
        return 5 + num;
      },
      methodToTest() {
        return this.foo(1) + this.foo(2);
      },
    };
    
    module.exports = obj;
    

    index.test.js:

    const obj = require('./');
    const sinon = require('sinon');
    
    describe('68463040', () => {
      it('should pass', () => {
        function fakeFoo(arg) {
          if (arg == 1) {
            return 6;
          }
          if (arg == 2) {
            return 7;
          }
        }
        sinon.replace(obj, 'foo', fakeFoo);
        const actual = obj.methodToTest();
        sinon.assert.match(actual, 13);
      });
    });
    

    test result:

      68463040
        ✓ should pass
    
    
      1 passing (3ms)
    
    ----------|---------|----------|---------|---------|-------------------
    File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ----------|---------|----------|---------|---------|-------------------
    All files |      75 |      100 |      50 |      75 |                   
     index.js |      75 |      100 |      50 |      75 | 3                 
    ----------|---------|----------|---------|---------|-------------------