Jazzuzz Jazzuzz - 4 months ago 42x
Node.js Question

Express JS Integration testing with Supertest and mock database

Is it possible to test an Express JS REST API using supertest but replacing the actual database connection with a mock database object? I have unit tests covering the database models and other parts of the application as well as functional tests of the API endpoints making actual database connections, but I have a weird requirement to create integration tests that are like the functional tests but use mock database connections. A sample endpoint controller is below:

var model = require('../../../lib/models/list');

module.exports = {
index: function(req, res) {
var data = { key: 'domains', table: 'demo.events'};

var dataModel = new model(data);

dataModel.query().then(function(results) {
res.respond({data: results}, 200);
}).fail(function(err) {
res.respond({message: 'there was an error retrieving data'}, 500);

And the index for the URI is

var express = require('express'), app, exports;
app = exports = module.exports = express();

exports.callbacks = require('./controller');

app.get('/', exports.callbacks.index);

The list model used in the controller connects to the database and retrieves the data that is output. The challenge is mocking that actual database call while still using supertest to make the request and retrieve the data from the URI

Any information would be helpful including if you think this is a bad or pointless idea


I have had limited success with 2 approaches:

1) use rewire to replace the database driver library like mongodb with a mocked one, perhaps using the spy/stub/mock capabilities of sinon

2) Set your db as an app setting via app.set('mongodb', connectedDb) for dev/prod but in test environment set a mock database instead. This requires your db-accessing code (models typically) to get the DB from the app, or otherwise be mock-friendly or designed with a dependency injection pattern.

Neither of these make everything clean and painless, but I have gotten some utility out of them.