Unit testing Express/Mongoose app routes without hitting the database Unit testing Express/Mongoose app routes without hitting the database mongoose mongoose

Unit testing Express/Mongoose app routes without hitting the database


I believe the answer you are looking for can be found at this video:Unit Testing Express Middleware / TDD with Express and Mocha

I have decided to follow It's instructions and It has been great so far. The thing is to split your routes between routes and middlewares, so you can test your business logic without calling or starting a server. Using node-mocks-http you can mock the request and response params.

To mock my models calls I am using sinon to stub methods like get, list and stuff that should hit the database. For your case the same video will provide an example of using mockgoose.

A simple example could be:

/* global beforeEach afterEach describe it */const chai = require('chai')const chaiAsPromised = require('chai-as-promised')const sinon = require('sinon')const httpMocks = require('node-mocks-http')const NotFoundError = require('../../app/errors/not_found.error')const QuestionModel = require('../../app/models/question.model')const QuestionAdminMiddleware = require('../../app/middlewares/question.admin.middleware')chai.use(chaiAsPromised)const expect = chai.expectlet reqlet resbeforeEach(() => {  req = httpMocks.createRequest()  res = httpMocks.createResponse()  sinon.stub(QuestionModel, 'get').callsFake(() => {    return new Promise((resolve) => {      resolve(null)    })  })})afterEach(() => {  QuestionModel.list.restore()  QuestionModel.get.restore()})describe('Question Middleware', () => {  describe('Admin Actions', () => {    it('should throw not found from showAction', () => {      return expect(QuestionAdminMiddleware.showAction(req, res))              .to.be.rejectedWith(NotFoundError)    })  })})