mocha sinon code example
Example 1: nodejs mocha mock
const chai = require("chai");
const expect = chai.expect;
const sinon = require("sinon");
const indexPage = require("../../controllers/app.controller.js");
describe("AppController", function() {
describe("getIndexPage", function() {
it("should send hey when user is logged in", function() {
let user = {
isLoggedIn: function(){}
}
const isLoggedInStub = sinon.stub(user, "isLoggedIn").returns(true);
let req = {
user: user
}
let res = {
send: function(){}
}
const mock = sinon.mock(res);
mock.expects("send").once().withExactArgs("Hey");
indexPage.getIndexPage(req, res);
expect(isLoggedInStub.calledOnce).to.be.true;
mock.verify();
});
});
});
Example 2: sinon js
Sinon provides standalone test spies, stubs and mocks for JavaScript.
It works with any unit testing framework.
Spy -> Monitoring and verifying function behaviour
Stub -> Modify function behaviour / Replace difficult to test code
Mock -> Fake method for verifying multiple specific behaviours