# Testing the Data Layer with mongodb-memory-server

mongodb-memory-server starts a real, throwaway MongoDB for a test file, the way the helper in every exercise of this course does, so before starts it, beforeEach puts the same documents back for every test, node --test and assert check the data layer, Supertest checks a route, and after stops it, never touching your own data.

Journeyman · MongoDB · Node.js · Unit Testing · Updated November 19, 2026

By Gregor Dzierzon

## After this lesson you can

- Start a throwaway MongoDB for a test file with mongodb-memory-server in before, seed it in beforeEach, and stop it in after
- Test data-layer functions with node --test and assert, and a route with Supertest, against the throwaway database
- Choose where database work belongs in a Node app, from the one client in server.js to the data layer, a route, the error handler and a test hook

## Key takeaways

- Tests that use your own database can change your data, and they pass or fail depending on what happens to be in it that day.
- 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 the folder.
- beforeEach empties the database and saves the same documents again, so every test starts the same way, whatever ran before it.
- A data-layer test calls a function and checks what it gives back with assert, and a Supertest test sends a request to createApp(db) and checks the answer.

A data layer is where the quiet bugs live: a filter with a typo finds nothing, a sort in the wrong direction shows the oldest pets first, and no error says so. Tests catch them, as long as each test runs against a real MongoDB holding data it knows. Since your first exercise, every `npm test` in this course has started such a database for you. This lesson opens up how, so you can write the same tests for any app's data layer.

The examples test the pet API's data layer from *A Data Layer: One File That Talks to the Database*.

## Why not test against your own database

Point the pet API's tests at your `maple_street` database, and three things go wrong. A test that adds Ziggy adds him for real, and the next run finds two. A test that expects three cats fails the day a volunteer adds a fourth. And a teammate who clones the project, or a computer that runs the tests on GitHub, has no `maple_street` at all.

Tests need what a cooking show has: a fresh kitchen for every episode, set up the same way each time and cleared away afterward. **mongodb-memory-server** is that kitchen. It starts a real MongoDB program in a temporary folder, on a free port, for one test file, and removes it at the end. Because it's real MongoDB, every filter, index and error behaves as it will for your users. The tests install it as a development package, next to Supertest:

```bash
npm install --save-dev mongodb-memory-server supertest
```

## The helper you've been using, opened up

Every exercise in this course has a file you didn't need to read: `test/mongosh-helper.js`. Its middle part is the kitchen:

```javascript
export function startTestDatabase() {
  before(async () => {
    const installed = installedMongoDB();
    server = await MongoMemoryServer.create(installed ? { binary: { systemBinary: installed } } : {});
    client = await MongoClient.connect(server.getUri());
    database = client.db("exercise");
  });

  beforeEach(async () => {
    await database.dropDatabase();
    for (const file of readdirSync(dataFolder).filter((name) => name.endsWith(".json"))) {
      // Extended JSON, so dates, ids and decimals in the data come back as their real types.
      const documents = BSON.EJSON.parse(readFileSync(new URL(file, dataFolder), "utf8"));
      await database.collection(file.replace(".json", "")).insertMany(documents);
    }
  });

  after(async () => {
    await client?.close();
    await server?.stop();
  });
}
```

`before`, `beforeEach` and `after` come from `node:test`, Node's built-in test runner. They're **hooks**: functions the runner calls around your tests. `before` runs once, before the file's first test: `MongoMemoryServer.create()` starts the server, and `getUri()` gives its connection string, such as `mongodb://127.0.0.1:61848/`, with a new port each time. `beforeEach` runs before every test: it drops the whole database and loads each file in `data/` again, so every test starts with the same recipes or pets. `after` closes the client, then stops the server, which deletes its folder. (`?.` is read "if it's there": it skips the call when the server never started.)

![A timeline of one test file from left to right: before starts a throwaway MongoDB, beforeEach puts the three cats back, test 1 runs, beforeEach puts the three cats back again, test 2 runs, and after stops the throwaway MongoDB. Off to one side, your own maple_street database is never touched.](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/c3eeda72438d48ea8bed54b9777db20c.webp)

`installedMongoDB()`, higher up in the file, looks for the MongoDB you installed in *Setup: MongoDB, mongosh and Compass*, and uses that program. Without one, the first run downloads MongoDB into a cache folder, once per computer: about 950 MB on Windows and about 180 MB on a Mac. The version comes from `package.json`'s `"config"` part, so every computer tests against the same MongoDB.

## Tests for the pet data layer

The same three hooks start the tests for the pet API. Make `test/pets.test.js`. Its `before` also hands the throwaway database to the data layer, and its `beforeEach` saves three cats:

```javascript
import { test, before, beforeEach, after } 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 { useDatabase, listPets, addPet } from "../data/pets.js";
import { createApp } from "../app.js";

let server;
let client;
let db;

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

beforeEach(async () => {
  await db.dropDatabase();
  await db.collection("pets").insertMany([
    { _id: new ObjectId("6740c0000000000000000002"), name: "Mochi", species: "cat", age: 2, traits: ["calm"], status: "available" },
    { _id: new ObjectId("6740c0000000000000000005"), name: "Juniper", species: "cat", age: 5, traits: ["good with kids"], status: "adopted" },
    { _id: new ObjectId("6740c0000000000000000007"), name: "Olive", species: "cat", age: 9, traits: ["good with kids"], status: "available" },
  ]);
});

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

This file starts the server the plain way, so on a computer with no MongoDB installed, its first run downloads one. The exercises in this module keep the same hooks in `test/test-database.js`, with the search for your installed MongoDB added, as in the helper above.

Now the tests themselves. A data-layer test calls a function and checks what it gives back with `assert`. `assert.deepEqual` compares two values item by item, and `assert.equal` compares one value. The second test checks the database itself, since saving is the whole point of `addPet`:

```javascript
test("listPets for cats that are good with kids gives Juniper and Olive", async () => {
  const pets = await listPets({ species: "cat", goodWithKids: true, page: 1 });
  assert.deepEqual(pets.map((pet) => pet.name), ["Juniper", "Olive"]);
});

test("addPet saves Ziggy as available", async () => {
  await addPet({ name: "Ziggy", species: "cat", age: 4, traits: ["playful"] });
  const saved = await db.collection("pets").findOne({ name: "Ziggy" });
  assert.equal(saved.status, "available");
});
```

Because `beforeEach` puts the three cats back every time, Ziggy is gone before the next test starts: tests that can't affect each other are called **isolated**.

## Supertest for a route

A route test goes one step further. Supertest's `request(createApp(db))` sends a request straight to the app, with no server running, and the answer comes back through the route, the data layer and a real MongoDB. A test of parts working together like this is called an **integration test**:

```javascript
test("GET /pets/2 answers 400", async () => {
  const response = await request(createApp(db)).get("/pets/2");
  assert.equal(response.status, 400);
});
```

Run all three with `node --test`:

```text
✔ listPets for cats that are good with kids gives Juniper and Olive (1188.0229ms)
✔ addPet saves Ziggy as available (9.7862ms)
✔ GET /pets/2 answers 400 (21.9383ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 1695.9733
```

The first test takes about a second, because that's when the server starts; your times will differ. Now make the quiet bug: type `"good with kid"` in `listPets`, without the s, and run the tests again. No error, an empty list, and a test that says exactly what went wrong:

```text
✖ listPets for cats that are good with kids gives Juniper and Olive (1052.8349ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
  + actual - expected

  + []
  - [
  -   'Juniper',
  -   'Olive'
  - ]
```

## Check yourself

2 questions to try on the lesson page.

## So what

A real MongoDB that appears for your tests and disappears after them means every change to the data layer is checked against what your users will really get, on any computer, and your own data is never touched.

## Key terms

- [mongodb-memory-server](https://www.ask-codey.com/glossary/mongodb-memory-server)
- [node:test](https://www.ask-codey.com/glossary/node-test)
- [Integration Test](https://www.ask-codey.com/glossary/integration-test)
- [Test Isolation](https://www.ask-codey.com/glossary/test-isolation)
- [Supertest](https://www.ask-codey.com/glossary/supertest)

## Related

- [A Data Layer: One File That Talks to the Database](https://www.ask-codey.com/lessons/mongodb-driver-a-data-layer)
- [When the Database Says No: Bad ids, Duplicates and Not Found](https://www.ask-codey.com/lessons/mongodb-driver-when-the-database-says-no)
- [Exercise: Recipe Finder](https://www.ask-codey.com/lessons/exercise-mongodb-recipe-finder)

Source: https://www.ask-codey.com/lessons/mongodb-driver-testing-with-mongodb-memory-server
