Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 37 ยท Testing

Testing Queries with node:test

Write real tests for repository code with node:test and assert: arrange data, act, assert on rows, test constraints, transactions and migrations up and down.

A repository (or a service that wraps Repository/Model calls) has a simple job: given some data in the database, return the right rows or make the right change. That is easy to test and very valuable. In this lesson you will write tests in the Arrange, Act, Assert shape using Node's built-in node:test runner and node:assert/strict, which need no installation.

Everything here is runnable. The repository under test is a small hand-written module on node:sqlite standing in for a TypeORM Repository or a Sequelize Model; the structure of the tests is exactly what you would write against the real libraries.

Stand-in. The UserRepo below is our own code, not TypeORM or Sequelize. Replace its body with repo.find(...) or User.findAll(...) and the tests keep their shape.

Running tests on this page

A test runner normally runs from a terminal with node --test. The editor here cannot show a terminal, so the examples write a test file to disk, execute it through the runner's programmatic API (run()) and print one stable line per test. On your machine you would simply run node --test.

Node.js A repository and its tests

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.

Four habits are visible in this file:

  1. One fresh database per test (beforeEach), so tests never depend on each other or on order.
  2. Arrange, Act, Assert: create data, call one method, check the result.
  3. Test the failure paths such as the unknown email and the duplicate. Constraint behavior is something only a real database can verify.
  4. Assert on observable results (rows returned), not on which SQL was generated.

Testing a transaction

A transactional function has two promises: success commits everything, failure leaves no trace. Test both.

Node.js Test commit and rollback

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 order of statements matters in the failing test: the credit runs first, then the debit breaks the check. Only a test that asserts the final balances proves the rollback really happened.

Testing migrations

A migration deserves one test: run it up, check the schema, run it down, check again. Bugs in down are common because nobody exercises it until a deployment goes wrong.

Node.js Test up and down

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.

Running against the real libraries

With the packages installed, the same tests run with node --test (TypeScript projects often use tsx --test or compile first). The only differences are in setup:

TypeScript
// read-only: real TypeORM setup for the same style of test
import { before, beforeEach, after, describe, it } from 'node:test';
import assert from 'node:assert/strict';

describe('UserRepo', () => {
  before(async () => { await testSource.initialize(); });
  beforeEach(async () => { await testSource.synchronize(true); }); // drop and recreate
  after(async () => { await testSource.destroy(); });

  it('finds a user by email', async () => {
    const repo = testSource.getRepository(User);
    await repo.save({ email: '[email protected]' });
    assert.equal((await repo.findOneBy({ email: '[email protected]' }))?.email, '[email protected]');
  });
});

Remember to close the connection in after, or the test process will not exit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why create a new database in beforeEach?

    Isolation makes tests order-independent and easy to debug.
  2. 2. What does a good transaction test assert after a failure?

    Atomicity means no partial changes; only checking final data proves it.
  3. 3. Which assertion checks that a function throws?

    assert.throws runs the function and passes only if it throws (optionally matching a pattern).
  4. 4. Why test a migration's down step?

    A broken down is only discovered during an emergency unless a test runs it.

Summary

  • Test repository code against a real database with fresh state per test.
  • Follow Arrange, Act, Assert and cover failure paths: constraints, unknown ids, rollbacks.
  • Check final data to prove a transaction rolled back.
  • Test migrations both ways, and remember to close connections in real setups.

Next: Factories and Mocks