Testing with mongodb-memory-server

mongodb-memory-server starts a real, throwaway MongoDB for a test file, so before starts it, beforeEach gives every test the same fresh data, Supertest tests the whole API against it, and after stops it, with your own data never touched.

Journeyman · Node.js · Unit Testing · MongoDB · Updated

By

After this lesson you can

  • Start a throwaway MongoDB for a test file with mongodb-memory-server in before, and stop it in after
  • Give every test the same starting data with beforeEach, and test the API end to end with Supertest against the throwaway database

Key takeaways

  • Tests that run against your own database can delete your data, and they pass or fail depending on what happens to be in it.
  • mongodb-memory-server starts a real MongoDB in a temporary folder, on a free port. MongoMemoryServer.create() starts it, and getUri() gives its connection string.
  • before starts the throwaway database once for the test file, and after closes the client and stops it, which deletes its folder.
  • beforeEach empties the collection and saves the same documents again, so every test starts the same way, whatever ran before it.
  • The first run downloads MongoDB once per computer, unless the tests use the MongoDB you installed. After that, the tests run offline.

An API's database code is where the worst bugs hide: a filter that finds too much, an update that changes the wrong workout. Tests that run against a real MongoDB catch them, and the database exercises from here on check your work that way. This lesson shows how those tests get a database of their own.

Why not test against your own database

Point Rep Counter's tests at the rep_counter database on your computer, and three things go wrong. A test that deletes a workout deletes one of yours. A test that expects three workouts fails the day you add a fourth by hand. And a teammate who clones your project, or the computer that runs your tests on GitHub, has no MongoDB with your data in it.

Tests need what a cooking show has: a fresh kitchen for every episode, set out the same way each time, and cleaned away afterward. mongodb-memory-server is that kitchen. It starts a real MongoDB server in a temporary folder, on a free port, for one test file, and stops it at the end. It's real MongoDB, so every filter and update behaves exactly as it will for your users. It goes in as a development package, beside Supertest:

npm install --save-dev mongodb-memory-server

A throwaway MongoDB: before and after

node:test has hooks: functions it runs around your tests. before runs once, before the file's first test, and after runs once, after its last. Here they start the throwaway server and stop it again:

import { test, before, after, beforeEach } from "node:test";
import assert from "node:assert/strict";
import request from "supertest";
import { MongoMemoryServer } from "mongodb-memory-server";
import { MongoClient, ObjectId } from "mongodb";
import { createApp } from "./app.js";

let mongo;
let client;
let db;

before(async () => {
  mongo = await MongoMemoryServer.create();
  client = new MongoClient(mongo.getUri());
  await client.connect();
  db = client.db("rep_counter");
});

after(async () => {
  await client.close();
  await mongo.stop();
});

MongoMemoryServer.create() starts the server, and getUri() gives its connection string, such as mongodb://127.0.0.1:64215/, with a new port each time. From there it's the client you know. after closes the client first, then stops the server, which deletes its folder.

A fresh start for every test: beforeEach

beforeEach runs before every test. It empties the collection and saves the same workout again, with an _id of its own choosing, so the tests can ask for it by that id:

const danaId = new ObjectId("6740a1000000000000000001");

beforeEach(async () => {
  await db.collection("workouts").deleteMany({});
  await db.collection("workouts").insertOne({
    _id: danaId,
    member: "Dana",
    date: "2026-11-16",
    sets: [{ exercise: "squat", reps: 8, weight: 135 }],
  });
});

Without it, a test that deletes Dana's workout would leave it deleted for every test after it, and the tests would pass or fail by the order they ran in. Tests that can't affect each other are called isolated, and this is what keeps them that way.

Supertest against the real thing

The tests are the Supertest tests you know, with one difference: each one hands createApp the throwaway database. That's what createApp(db) was for:

test("GET /workouts/:id answers 200 with Dana's workout", async () => {
  const response = await request(createApp(db)).get("/workouts/6740a1000000000000000001");
  assert.equal(response.status, 200);
  assert.equal(response.body.member, "Dana");
  assert.equal(response.body.id, "6740a1000000000000000001");
});

test("a workout deleted from the database answers 404", async () => {
  await db.collection("workouts").deleteOne({ _id: danaId });
  const response = await request(createApp(db)).get("/workouts/6740a1000000000000000001");
  assert.equal(response.status, 404);
});

test("GET /workouts/not-an-id answers 404 with the error shape", async () => {
  const response = await request(createApp(db)).get("/workouts/not-an-id");
  assert.equal(response.status, 404);
  assert.deepEqual(response.body, {
    status: 404,
    title: "Not Found",
    detail: "There's no workout not-an-id.",
  });
});

Each request goes through the route, the repository and a real MongoDB, and back. A test that checks the parts working together like this is called an integration test. Run node --test, and the last lines say:

ℹ tests 3
ℹ pass 3
ℹ fail 0

The first run, and the exercises' helper

mongodb-memory-server needs a MongoDB program to start. With none named, the first run downloads one into a cache folder in your home folder, once per computer: about 950 MB on Windows and about 180 MB on a Mac. After that, tests run offline. The exercises pin the version in package.json, so every computer tests against the same MongoDB:

"config": {
  "mongodbMemoryServer": {
    "version": "9.0.8",
    "disablePostinstall": "true",
    "systemBinaryVersionCheck": "false"
  }
}

Every database exercise in this course comes with a file, throwaway-database.js, that does all of the above for you: its before starts the server, its beforeEach empties the database, and its after stops it. One thing more: it looks for the MongoDB you installed in Setup: MongoDB and Compass, and when it finds one, it uses that program, so nothing is downloaded at all.

Check yourself

2 questions to try on the lesson page.

So what

A real database that appears for your tests and vanishes after them means tests that check what your users will really get, on any computer, without ever touching your own data.

Key terms

Related