I am trying to test my function using Sinon stubs and mocks, but I am getting an error. Please suggest me right technique to write it

In this module I want to test searchAll function which is calling findAll function of some other module, so I am trying to stub findAll function of the other module and mock the res in my test.js module.

UseControllerModule.js

exports.searchAll = (req, res) => {
    Users.findAll((err, data) => {
        if (err)
            res.status(500).send({
                message: err.message || "Some error occured while retrieving data",
            });
        else res.send(data);
    });
};

The findAll function of the other module has userid parameter which has been stubbed.

So after stubbing and getting the value in response I am trying to mock response here, but it is not running. Mock verifications are causing errors. If I remove verifications, the test cases pass but it does not increment any test coverage.

Test.js

describe("searchAll", function() {
    let res;

    beforeEach(() => {
        res = {
            json: function() {},
        };
    });

    it("should return all the id's of  members of the club", async function() {
        const stubvalue = {
            userid: faker.random.uuid(),
        };
        const mock = sinon.mock(res);
        mock.expects("json").withExactArgs({
            data: stubValue
        });

        const stub = sinon.stub(UserModel, "findAll").returns(Stubvalue);
        const user = await UserController.searchAll();
        expect(stub.calledOnce).to.be.true;
        mock.verify();
        stub.restore();

    });
});

1 thought on “I am trying to test my function using Sinon stubs and mocks, but I am getting an error. Please suggest me right technique to write it”

  1. You should use stub.callsFake(fakeFunction); to provide a fake implementation for UserModel.findAll() method. It accepts a callback parameter, so you need to execute it and pass the stubvalue to that callback in your fake implementation manually.

    UseControllerModule.js:

    const Users = require('./UserModel');
    
    exports.searchAll = (req, res) => {
      Users.findAll((err, data) => {
        if (err) {
          res.status(500).send({
            message: err.message || 'Some error occured while retrieving data',
          });
        } else {
          res.send(data);
        }
      });
    };
    

    UserModel.js:

    module.exports = {
      findAll(callback) {
        console.log('real implementation');
        callback(null, 'real data');
      },
    };
    

    UseControllerModule.test.js:

    const sinon = require('sinon');
    const { expect } = require('chai');
    const UserModel = require('./UserModel');
    const UserController = require('./UseControllerModule');
    
    describe('searchAll', function () {
      let res;
    
      beforeEach(() => {
        res = {
          send: function () {},
        };
      });
    
      it("should return all the id's of  members of the club", async function () {
        const stubvalue = {
          userid: '123',
        };
        const mock = sinon.mock(res);
        mock.expects('send').withExactArgs(stubvalue);
    
        const stub = sinon.stub(UserModel, 'findAll').callsFake((callback) => {
          callback(null, stubvalue);
        });
        UserController.searchAll({}, res);
        expect(stub.calledOnce).to.be.true;
        mock.verify();
        stub.restore();
      });
    });
    

    unit test result:

      searchAll
        ✓ should return all the id's of  members of the club
    
    
      1 passing (6ms)
    
    ------------------------|---------|----------|---------|---------|-------------------
    File                    | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ------------------------|---------|----------|---------|---------|-------------------
    All files               |   66.67 |       25 |   66.67 |   66.67 |                   
     UseControllerModule.js |   83.33 |       25 |     100 |   83.33 | 6                 
     UserModel.js           |   33.33 |      100 |       0 |   33.33 | 3-4               
    ------------------------|---------|----------|---------|---------|-------------------
    
    Reply

Leave a Comment