Stop 13 · Testing & DeploymentTopics · 3/10

Testing with an In-Memory MongoDB

Part of the MERN Stack Roadmap

In short

API tests that mock Mongoose miss real bugs, and tests that hit your dev database leave a mess behind. mongodb-memory-server gives every test run a brand new, real MongoDB that disappears when the tests finish.

mongodb-memory-server starts a temporary MongoDB inside your test run, so API tests can use real Mongoose queries without touching your development or production data.

The jaadu in a chef's apron cooks on a small, spotless practice stove inside a glass box, while a big busy kitchen hums in the background.

Think of it like this

The practice kitchen

A cooking school doesn't let students practise in the hotel's main kitchen during dinner service. Each batch gets a fresh practice kitchen with real stoves and real ingredients. When class ends, it is cleaned and closed. Your tests get the same: a real MongoDB that nobody else uses and nobody has to clean up.

Watch it happen

One test run

beforeAll
Tests
afterEach
afterAll

1/4Start MongoMemoryServer, get its URI and call mongoose.connect(uri).

The big ideas

What you need to know

A real database, briefly

It downloads a MongoDB binary once, then starts it in a temp folder for each test run. Queries, indexes and validation behave like the real thing.

Separate app from server

Export the Express app from app.js and call app.listen only in server.js, so Supertest can use the app without opening a port.

Clean between tests

Wipe collections in afterEach so tests don't depend on each other's data or order.

Transactions need a replica set

If your code uses transactions, use MongoMemoryReplSet instead of MongoMemoryServer.

See it in code

Walk through the code

js
1// tests/products.test.js2import mongoose from "mongoose";3import request from "supertest";4import { MongoMemoryServer } from "mongodb-memory-server";5import app from "../src/app.js";6 7let mongo;8 9beforeAll(async () => {10  mongo = await MongoMemoryServer.create();11  await mongoose.connect(mongo.getUri());12});13 14afterEach(async () => {15  const collections = await mongoose.connection.db.collections();16  await Promise.all(collections.map((c) => c.deleteMany({})));17});18 19afterAll(async () => {20  await mongoose.disconnect();21  await mongo.stop();22});23 24test("creates a product and lists it", async () => {25  const created = await request(app)26    .post("/api/products")27    .send({ name: "Masala Chai Kit", price: 249 })28    .expect(201);29 30  expect(created.body._id).toBeDefined();31 32  const res = await request(app).get("/api/products").expect(200);33  expect(res.body.products).toHaveLength(1);34  expect(res.body.products[0].name).toBe("Masala Chai Kit");35});36 37test("rejects a negative price", async () => {38  await request(app).post("/api/products").send({ name: "Pen", price: -5 }).expect(400);39});

1/5Start the in-memory server once for this file and connect Mongoose to it.

Jest plus Supertest against a throwaway MongoDB. Run Jest with ESM support or use Babel, as your project prefers.

Save yourself the pain

Common mistakes

Oops

Pointing tests at MONGO_URI from your .env file.

Do this instead

Tests can wipe collections. Always use the in-memory URI so real data is never touched.

Oops

Calling app.listen() inside app.js.

Do this instead

Keep app.js free of listen. Tests import the app, server.js starts it.

Oops

Writing tests that only pass when run in a certain order.

Do this instead

Clean data in afterEach and create what each test needs inside that test.

Your mission

Test your notes API

~45 min

Quick check

Why is afterEach used to clear collections?

Go deeper

  1. 1Start the in-memory server in beforeAll and stop it in afterAll.
  2. 2Clear collections between tests so each test starts clean.
  3. 3Seed only the data each test needs.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge