Testing Mongoose with Jest
If you choose to delve into dangerous waters and test Mongoose apps with Jest, here’s what you need to know:
If you are using Jest <=26
, do not use Jest’s default when testing Mongoose apps, unless you are explicitly testing an application that only uses Mongoose’s browser library. In Jest >=27
, , so this is no longer an issue.
The jsdom
test environment attempts to create a browser-like test environment in Node.js, and it comes with numerous nasty surprises like a stubbed function that silently fails after tests are finished. Mongoose does not support jsdom in general and is not expected to function correctly in the jsdom
test environment.
Absolutely do not use when testing Mongoose apps. This is especially important if you’re using Jest >=25
, which stubs out process.nextTick()
.
Fake timers stub out global functions like setTimeout()
and setInterval()
, which causes problems when an underlying library uses these functions. Mongoose and 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.
If you absolutely must use timer mocks, make sure you import Mongoose before calling :
A better alternative is to create your own wrapper around setTimeout()
and stub that instead using sinon.
Do not use globalSetup
to call mongoose.connect()
or mongoose.createConnection()
. Jest runs in a , so you cannot use any connections you create in globalSetup
in your tests.
Want to learn how to test Mongoose apps correctly? The RESTful Web Services with Node.js and Express course on Pluralsight has a great section on testing Mongoose apps with .