Mocking Mongoose 243,355 teaches you nothing about MongoDB 1,815 . mongodb-memory-server 2,853 (github.com/typegoose/mongodb-memory-server (https://github.com/typegoose/mongodb-memory-server 2,853 ), MIT, version 11.3.0) downloads a real mongod on first use, starts it on a random free port with its storage in a temporary directory, and hands you the URI. The queries, the casting and the index errors are real; only the lifetime is short. Built-in Test Runner covers the node:test runner, Testing React Applications the React 7,897 side.
Three helpers are enough: startDatabase() calls MongoMemoryServer.create() and connects Mongoose to its URI, clearDatabase() runs deleteMany({}) over mongoose.connection.collections, and stopDatabase() disconnects and stops the server.
before(startDatabase); after(stopDatabase);
beforeEach(async () => {
await clearDatabase(); // isolation: every test starts from this state
asimov = await Author.create({ name: 'Isaac Asimov', country: 'US' });
await Book.create([{ title: 'Foundation', year: 1951, authorId: asimov._id },
{ title: 'I, Robot', year: 1950, authorId: asimov._id }]);
});
test('rejects a book with an unknown genre', async () => {
await assert.rejects(
Book.create({ title: 'Dune', year: 1965, genre: 'western', authorId: asimov._id }),
/`western` is not a valid enum value/);
});$ node --test test/books.test.js ✔ lists books newest first (683.9006ms) ✔ rejects a book with an unknown genre (5.9562ms) ✔ starts from the same two books (8.1223ms) ℹ pass 3
The run took 1420 ms: the first test pays for the server start, the rest cost single-digit milliseconds. Two settings matter. The binary download is one-time per machine and version — 11.3.0 asks for 8.2.6 — and MONGOMS_SYSTEM_BINARY points the library at a mongod you already have, which is how these tests ran here with no network access: it warns about the mismatch and continues. And MongoMemoryServer.create() starts a standalone, so a transaction fails with This MongoDB deployment does not support retryable writes. Use MongoMemoryReplSet.create({ replSet: { count: 1 } }) when the code opens a session; it started in 827 ms here against 562 ms for the standalone.