Search code examples
unit-testingmockingsinon

How to return value of Sinon fake based on argument of function?


I'm trying to avoid use of older Sinon APIs and use Fakes only. Previously, I used to be able to mock the return value of a stub based on an argument like so:

sinon.stub().withArgs("arg1").returns("val1")

This would return val1 when arg1 is passed.

What is the equivalent of achieving this with Sinon fakes?


Solution

  • "sinon": "^8.1.1". There is no sinon.fake.withArgs() API, instead, we can use sinon.fake(func) API.

    Wraps an existing Function to record all interactions, while leaving it up to the func to provide the behavior.

    This is useful when complex behavior not covered by the sinon.fake.* methods is required or when wrapping an existing function or method.

    import sinon from 'sinon';
    
    describe('74965194', () => {
      it('should pass', () => {
        const stub = sinon.stub().withArgs('arg1').returns('val1');
        sinon.assert.match(stub('arg1'), 'val1');
      });
    
      it('should pass too', () => {
        const fake = sinon.fake((arg) => {
          if (arg === 'arg1') return 'val1';
        });
        sinon.assert.match(fake('arg1'), 'val1');
      });
    });
    

    Test result:

      74965194
        ✓ should pass
        ✓ should pass too
    
    
      2 passing (5ms)