Search code examples
node.jsunit-testingmocha.jschaisinon

How to mock an Express/Node.js middleware on a post route?


I´m writing some tests with chai and mocha and i am having some troubles. For example, in the route that i paste down here, the LOGOUT calls the isLoggedIn middleware that checks if a user exists in the session. For example, if a do this:

  it('Logout', function(done) {
    chai.request(baseURL)
    .post('/logout')
    .end(function(err, res) {
      expect(err).to.be.null;
      expect(res).to.have.status(204);
      done();
    });
  });

the test faills cause i get a 401 status code. I am new on this test stuffs. I understand that i have to use sinon to get mi test pass, but i can´t get the solution.

This is my route:

'use strict';

const express = require('express');
const createError = require('http-errors');
const router = express.Router();
const bcrypt = require('bcrypt');
const User = require('../models/User');

const {isLoggedIn} = require('../helpers/middlewares');

router.post('/logout', isLoggedIn(), (req, res, next) => {
	req.session.destroy();
	return res.status(204).send();
});

This is the Middleware:

'use strict';

const createError = require('http-errors');

exports.isLoggedIn = () => (req, res, next) => {
  if (req.session.user) {
    next();
  } else {
    next(createError(401));
  };
};

Thank you very much!!!


Solution

  • In your flow problem in that express middleware initialized during run express application and after becomes unavailable for stubbing. My solution is that would init stub before run express application.

    test.spec.js:

    const chai = require("chai"),
        sinon = require("sinon"),
        chaiHttp = require("chai-http"),
        initServer = require("./initTestServer"),
        isLoggedInMiddleware = require("./middleware");
    
    chai.use(chaiHttp);
    const { expect } = chai;
    
    describe("Resource: /", function() {
        before(function() {
            sinon.stub(isLoggedInMiddleware, "isLoggedIn").callsFake(function() {
                return (req, res, next) => {
                    next();
                };
            });
    
            this.httpServer = initServer();
        });
    
        after(function() {
            this.httpServer.close();
        });
    
        describe("#POST /login", function() {
            beforeEach(function() {
                this.sandbox = sinon.createSandbox();
            });
    
            afterEach(function() {
                this.sandbox.restore();
            });
    
            it("- should login in system and return data", async function() {
                return chai
                    .request(this.httpServer.server)
                    .post("/logout")
                    .end((err, res) => {
                        expect(err).to.be.null;
                        expect(res).to.have.status(204);
                    });
            });
        });
    });
    

    initTestServer.js:

    const isLoggedInMiddleware = require("./middleware");
    
    const initServer = () => {
        const express = require("express");
        const app = express();
    
        app.post("/logout", isLoggedInMiddleware.isLoggedIn(), (req, res, next) => {
            return res.status(204).send();
        });
    
        const server = require("http").createServer(app);
        server.listen(3004);
    
        const close = () => {
            server.close();
            global.console.log(`Close test server connection on ${process.env.PORT}`);
        };
    
        return { server, close };
    };
    
    module.exports = initServer;