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();
});
});
You should use
stub.callsFake(fakeFunction);
to provide a fake implementation forUserModel.findAll()
method. It accepts a callback parameter, so you need to execute it and pass thestubvalue
to that callback in your fake implementation manually.UseControllerModule.js
:UserModel.js
:UseControllerModule.test.js
:unit test result: