Search code examples
node.jsmocha.jssinon

Sinon callCount is always zero


In my node js application has a file called index.js. Below is the code for the file.

function initiateProcess(pattern){
    run();
};

function run(){
    console.log('run called');  
}

module.exports ={initiateProcess,run}

For this file I added a test case. In that I am trying to validate if run was called at least once.

const chai= require('chai');
const server =require('./index');
const sinon =require('sinon');
const { expect } = chai;

describe('entry point test suite',()=>{
    it('should call function every second',()=>{
        const pattern= '* * * * * *';
        let spy = sinon.spy(server,'run');              
        server.initiateProcess(pattern);
        expect(spy.callCount).greaterThan(0);
    })
});

But callCount is always zero. I am new to sinon. what am I doing wrong here.


Solution

  • This isn't really a Sinon issue, it's really just down to how JavaScript works.

    initiateProcess references run which is declared inside your module, when you export via

    module.exports = { initiateProcess, run }
    

    The run function being exported is not the same run function being called inside initiateProcess, it's a copy.

    For this to work, you need to ensure the run function being mocked is the same one being called inside initiateProcess, here's how you can do that:

    module.exports = {
      initiateProcess(pattern) {
        this.run();
      }
      run() {
        console.log('run called');
      }
    }