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();

    });
});

10 thoughts 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”

Leave a Comment