showing results for - "nodejs mocha mock"
Isabel
29 Nov 2018
1const chai = require("chai");
2const expect = chai.expect;
3const sinon = require("sinon");
4const indexPage = require("../../controllers/app.controller.js");
5
6describe("AppController", function()  {
7  describe("getIndexPage", function() {
8    it("should send hey when user is logged in", function() {
9      // instantiate a user object with an empty isLoggedIn function
10      let user = {
11        isLoggedIn: function(){}
12      }
13
14      // Stub isLoggedIn function and make it return true always
15      const isLoggedInStub = sinon.stub(user, "isLoggedIn").returns(true);
16
17      // pass user into the req object
18      let req = {
19        user: user
20      }
21
22      // Have `res` have a send key with a function value coz we use `res.send()` in our func
23      let res = {
24        send: function(){}
25      }
26
27      // mock res
28      const mock = sinon.mock(res);
29      // build how we expect it t work
30      mock.expects("send").once().withExactArgs("Hey");
31
32      indexPage.getIndexPage(req, res);
33      expect(isLoggedInStub.calledOnce).to.be.true;
34
35      // verify that mock works as expected
36      mock.verify();
37    });
38  });
39});