Search code examples
javascripttestingasync-awaitsinonstub

sinon.js : stub call does not increment callCount


sinon.js 9.0.2

In test I create a stub:

test.js

const myHandler = {
  handle: (some_var_to_pass) => sinon.stub()["resolves"]([{ whatever: "whatever" }]),
};

Then hit the actual code from the test as some endpoint request (with async / await) which executs the code below:

code.js

module.exports = (myHandler) => ({
  getStuff: async (req, res, next) => {
  const var1 = "something1";
  const var2 = "something2";
  const my_response = await myHandler.handle()(var1, var2);

  console.log("my response", JSON.stringify(my_response)); //correct, returns { whatever: "whatever"}
  console.log("Executed stub: ", myHandler.handle(some_var_to_pass).callCount); //always returns zero

I control that myHandler.handle correctly goes through the stub creation and the my_response is

{ whatever: "whatever"}

However, myHandler.handle().callCount remains zero (not undefined). What am I missing to make it increment correctly? Or I need to actually set .callCount return to 1 when I create the stub (would be weird)?


Solution

  • You didn't stub myHandler.handle method. You only stub the function which myHandler.handle method returned. Unit test solution:

    code.js:

    module.exports = (myHandler) => ({
      getStuff: async (req, res, next) => {
        const var1 = 'something1';
        const var2 = 'something2';
        const my_response = await myHandler.handle()(var1, var2);
        return my_response;
      },
    });
    

    code.test.js:

    const code = require('./code');
    const sinon = require('sinon');
    
    describe('64468517', () => {
      it('should pass', async () => {
        const returnedFn = sinon.stub().resolves([{ whatever: 'whatever' }]);
        const myHandler = {
          handle: sinon.stub().returns(returnedFn),
        };
        await code(myHandler).getStuff();
        expect(myHandler.handle.callCount).to.be.eq(1);
        sinon.assert.calledOnce(myHandler.handle);
        sinon.assert.calledWithExactly(returnedFn, 'something1', 'something2');
      });
    });
    

    unit test result:

      64468517
        ✓ should pass
    
    
      1 passing (13ms)
    
    ----------|---------|----------|---------|---------|-------------------
    File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ----------|---------|----------|---------|---------|-------------------
    All files |     100 |      100 |     100 |     100 |                   
     code.js  |     100 |      100 |     100 |     100 |                   
    ----------|---------|----------|---------|---------|-------------------