How to use mockgoose (or any other db mocking) in express app integration test How to use mockgoose (or any other db mocking) in express app integration test express express

How to use mockgoose (or any other db mocking) in express app integration test


I had the same problem as you. In my case, I solved using chai + chai-http and breaking the db connection and app in different files:

db.js:

const mongoose = require('mongoose');const config = require('../../config');mongoose.Promise = global.Promise;mongoose.set('debug', process.env.DEBUG != undefined);function open(){    return new Promise((resolve, reject) => {        if(process.env.DEBUG != undefined) {            let Mockgoose = require('mockgoose').Mockgoose;            let mockgoose = new Mockgoose(mongoose);            mockgoose.helper.setDbVersion("** your mongodb version **");            mockgoose.prepareStorage().then(function() {                mongoose.connect(config.db_test, (err, res) => {                  if (err) return reject(err);                  resolve();                });            }).catch(reject);        }else{            mongoose.connect(config.db, (err, res) => {              if (err) return reject(err);              resolve();            });        }    });}function close(){    return mongoose.disconnect();}module.exports = { close, open };

app.js:

const express = require('express');const bodyParser = require('body-parser');const api = require('./routes');app.use(bodyParser.urlencoded({ extended: false }));app.use(bodyParser.json());app.use('/api', api);module.exports = app;

test.js (for test):

const chai = require('chai');const chaiHttp = require('chai-http');const expect = chai.expect;const conn = require('./../utils/db'); // <-- db.jsconst app = require('../../app'); // <-- app.jschai.use(chaiHttp);describe('# Test', function(){    before(function(done) {        conn.open().then(() => done()).catch(done);    });    after(function(done){        conn.close().then(() => done()).catch(done);    });    it(`test something`, function(done){        chai.request(app) // <-- pass the app here            .get('/path/to/test')            .then((res) => {                // expects                done();              })              .catch((err) => {                  done(err);              });    });});

index.js (for development or production):

const conn = require('./utils/db'); // <-- db.jsconst app = require('./app'); // <-- app.jsconst config = require('./config'); conn.open().then(() => {    app.listen(config.port, () => {        // OK!    });});

I hope it works for you or anyone.