Testing Mongoose with Jest
Jest is a client-side JavaScript testing library developed by Facebook. Because Jest is designed primarily for testing React applications, using it to test Node.js server-side applications comes with a lot of caveats. We strongly advise against using Jest for testing any Node.js apps unless you are an expert developer with an intimate knowledge of Jest.
If you choose to delve into dangerous waters and test Mongoose apps with Jest, here’s what you need to know:
Do not use Jest’s default when testing Mongoose apps, unless you are explicitly testing an application that only uses Mongoose’s browser library.
To change your testEnvironment
to Node.js, add testEnvironment
to your jest.config.js
file:
Absolutely do not use when testing Mongoose apps. Fake timers stub out global functions like setTimeout()
and , which causes problems when an underlying library uses these functions. The MongoDB Node.js driver uses these functions for deferring work until the next tick of the event loop and for monitoring connections to the MongoDB server.
Mongoose devs have already refactored out code to avoid using setImmediate()
to defer work to the next tick of the event loop, but we can’t reasonably ensure that every library Mongoose depends on doesn’t use setImmediate()
.
To work around this, create your own wrapper around setTimeout()
and stub that instead using .
// time.js
exports.setTimeout = function() {
return global.setTimeout.apply(global, arguments);
// Tests
const time = require('../util/time');
sinon.stub(time, 'setTimeout');
Do not use globalSetup
to call mongoose.connect()
or mongoose.createConnection()
. Jest runs globalSetup
in a separate environment, so you cannot use any connections you create in globalSetup
in your tests.
Want to learn more about testing Mongoose apps? The course on Pluralsight has a great section on testing Mongoose apps with Mocha.