Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 37 ยท Testing

Factories and Mocks

Build test data factories with defaults and overrides, write fake repositories for fast unit tests and use node:test mock functions to spy on calls.

Two things make database tests painful: creating valid rows takes ten lines of boilerplate, and the database itself is slow when the question is only "does my service make the right decision?". Factories solve the first problem, fakes and mocks solve the second. Used together they keep integration tests short and unit tests instant.

The examples run on node:sqlite and node:test's mock helper. They are stand-ins for the patterns you would use with TypeORM repositories or Sequelize models, and the structure transfers directly.

Factories: valid data in one line

A factory builds a valid record with generated unique values, and lets the test override only what it cares about. Without it, adding a new required column to users means editing every test that inserts one.

Node.js A factory with sequences and overrides

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.

Notice three design choices: defaults are valid, values that must be unique come from a counter, and related rows (an author for a post) are created only if the test did not supply one. Libraries such as @faker-js/faker can generate realistic names and addresses; they are optional and not installed here. When you use random data, seed it so a failing run can be reproduced.

In a real project the factory body calls repo.save(repo.create(data)) (TypeORM) or User.create(data) (Sequelize) instead of raw SQL, which also runs your entity hooks and validation.

Fakes: a repository without a database

If your service depends on a repository interface, a unit test can hand it an in-memory fake. Define the interface by what the service needs, not by everything the ORM offers.

Node.js A fake repository for a service test

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.

(This block uses assert directly and collects results by hand; in a test file you would use test() from node:test as in Testing Queries with node:test.)

A fake is the right tool when the logic under test is a decision (normalization, duplicate rule). It is the wrong tool for checking that a query is correct: a fake Map will happily accept a query your real database would reject. That is what the integration tests are for.

Mocks and spies

A mock function records how it was called. Use one when the behavior to verify is an interaction: "was the email sent exactly once, with this address?"

Node.js mock.fn records calls

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.

Mock the boundary, not the world

Mock or fake Do not mock
Email, payment, HTTP APIs, the clock The ORM itself in most tests
A repository, when testing pure business rules Your own small helper functions

Mocking repo.find to return a canned list tells you nothing about whether the where clause is right. Keep a thin integration layer that runs queries for real, and let everything above it use fakes. If a test needs many mocks to run, it is usually a sign the unit under test does too much; see Repository and Unit of Work.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main benefit of a test data factory?

    When a column is added, you fix one factory instead of every test.
  2. 2. When is a fake repository the right tool?

    Fakes check logic; only a real database can confirm queries and constraints.
  3. 3. What does mock.fn() let you check?

    The mock records calls in mock.calls and exposes callCount().
  4. 4. Why seed a random data generator?

    Deterministic data makes failures repeatable.

Summary

  • Factories produce valid rows with unique values and optional overrides.
  • Fakes replace a repository for fast tests of business rules; integration tests still need a real database.
  • mock.fn() verifies interactions such as sending an email.
  • Mock external boundaries, not the ORM, and seed random data.

Next: Finding and Fixing N+1 Queries