Testing Mongoose with
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 jsdom
test environment when testing Mongoose apps, unless you are explicitly testing an application that only uses . In Jest >=27
, “node” is Jest’s default testEnvironment
, 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 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 timer mocks 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 .
Do not use globalSetup
to call mongoose.connect()
or mongoose.createConnection()
. Jest runs in a separate environment, so you cannot use any connections you create in globalSetup
in your tests.
Want to learn how to test Mongoose apps correctly? The course on Pluralsight has a great section on testing Mongoose apps with Mocha.