Chuyển đến nội dung

Bài 31 · Testing and Patterns

Testing Mongoose Code

Learn how to test Mongoose applications - unit tests without a database, integration tests with mongodb-memory-server, test isolation, factories and a repository pattern, using node:test.

Code that talks to a database is awkward to test: the database is slow, shared, and full of state left by earlier tests. A good Mongoose test strategy separates what can be tested without a database (validation, pure logic) from what genuinely needs one (queries, indexes, middleware that hits the database), and keeps each test isolated.

This lesson describes that strategy. The real mongodb-memory-server and Mongoose cannot run on this site, so the runnable examples use node:test with in-memory stand-ins, and every real-library snippet is read-only.

Three levels of tests

  1. Pure unit tests: validation rules, helper functions, services that receive their data as arguments. No database. Run in milliseconds.
  2. Unit tests with a fake: the service depends on a repository object; tests pass an in-memory fake.
  3. Integration tests: real Mongoose against a real (but disposable) MongoDB: indexes, unique constraints, populate, aggregations, transactions.

Most tests should be level 1 and 2; keep a smaller set of level 3 for behavior only MongoDB can prove (a unique index really rejecting duplicates, an aggregation returning the right totals).

flowchart TB
  A["Integration: real MongoDB<br/>few, slower"] --- B["Fakes: in-memory repository<br/>some"] --- C["Pure unit tests<br/>many, fastest"]

Wide base, narrow top: the test pyramid for data code.

Testing validation without a database

Mongoose validation runs without a connection: create a document and call validate(), or validateSync().

JavaScript
import test from 'node:test';
import assert from 'node:assert/strict';
import { User } from '../models/user.js';

test('email is required', async () => {
  const user = new User({ name: 'Ada' });
  await assert.rejects(user.validate(), (err) => {
    assert.ok(err.errors.email);
    return true;
  });
});

No mongoose.connect() is needed, so these tests are instant. This also works for custom validators, defaults, virtuals and getters and setters.

Running checks with node:assert

The example below tests a small validator the way you would test a custom schema rule. It uses the real node:assert module, which runs on the site, and prints its own report.

Node.js Running checks and reporting (runs for real)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In your project you would save the cases in user.test.js and run node --test; the built-in runner finds *.test.js files, and Jest or Vitest work equally well.

Integration tests with mongodb-memory-server

The mongodb-memory-server package downloads a MongoDB binary once and starts a throwaway mongod in a temp folder, on a random port, per test run. Read-only example:

JavaScript
import test, { before, after, beforeEach } from 'node:test';
import assert from 'node:assert/strict';
import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import { User } from '../models/user.js';

let mongod;

before(async () => {
  mongod = await MongoMemoryServer.create();
  await mongoose.connect(mongod.getUri());
  await User.init(); // wait until indexes (unique!) exist
});

beforeEach(async () => {
  await mongoose.connection.dropDatabase(); // clean slate for every test
  await User.init();
});

after(async () => {
  await mongoose.disconnect();
  await mongod.stop();
});

test('duplicate emails are rejected', async () => {
  await User.create({ name: 'Ada', email: '[email protected]' });
  await assert.rejects(User.create({ name: 'Bob', email: '[email protected]' }), { code: 11000 });
});

Important details: call Model.init() before testing a unique index, because index building is asynchronous and a test can run before the index exists; clear data between tests (drop the database, or deleteMany each collection); and disconnect at the end or the process hangs. Alternatively run a real MongoDB in Docker or a CI service container. Transactions need a replica set, so use MongoMemoryReplSet for those (see Transactions and sessions).

A fake repository for unit tests

Wrap database access in a small repository with an interface your service uses. Tests inject a fake; production injects the Mongoose implementation.

Node.js Service tested against a fake repository (runs for real)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The fake proves the business rule; one integration test proves that the real repository and the unique index behave the same way.

Test data: factories

Avoid copy-pasting object literals everywhere. A small factory builds valid objects and lets each test override only what it cares about:

JavaScript
let counter = 0;
export const buildUser = (overrides = {}) => ({
  name: 'Test User',
  email: `user${++counter}@example.com`,
  ...overrides,
});

await User.create(buildUser({ role: 'admin' }));

Unique counters keep unique indexes from colliding. Libraries like @faker-js/faker generate realistic data; seed them for repeatable tests.

Tips for reliable database tests

  • One database (or one memory server) per test process; clean between tests, not between files in parallel workers sharing a database.
  • Never point tests at a development or production URI; assert that the URI contains test or use the in-memory server.
  • Do not assert on _id values or timestamps; assert on behavior.
  • Wait for indexes (init()), and for autoIndex in test setup.
  • Keep integration tests few and meaningful: indexes, unique rules, aggregations, transactions, hooks that query.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Can you test Mongoose schema validation without connecting to MongoDB?

    Validation runs in memory on the document; no database connection is involved.
  2. 2. Why call Model.init() in a test before checking a unique constraint?

    Without it the unique index may not be built yet, producing flaky tests.
  3. 3. What is the main benefit of a repository interface?

    The service depends on an interface, so tests inject a fake; a few integration tests still verify the real implementation.
  4. 4. What does mongodb-memory-server give you?

    It starts a real temporary MongoDB, so integration tests exercise genuine behavior.

Summary

  • Test validation and pure logic without a database; it is instant.
  • Hide database access behind a repository so services can use an in-memory fake.
  • Use mongodb-memory-server (or Docker) for a few real integration tests, and call init().
  • Clean data between tests, use factories, and never point tests at real data.
  • Transactions need a replica set in tests.

Next: Schema plugins and reuse

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.