How-To Guide

How to Test Database Code with Test Containers

Test against a real database: spin up a throwaway container per suite, migrate it, isolate test data, and tear it down reliably.

On this page

  1. Introduction
  2. Start the real engine in a container
  3. Migrate to the current schema
  4. Isolate each test’s data
  5. Tear down reliably
  6. Test migrations and failures, not just the happy path
  7. Common pitfalls
  8. Conclusion

Introduction

Database code tested against a mock is tested against your assumptions, not the database. The mock returns what you told it to, so it cannot reveal that a query is invalid, that a constraint rejects the insert, that a type coerces differently than you expected, or that an isolation level behaves unlike your mental model. Those are exactly the bugs that reach production. A throwaway real database container tests against the actual engine.

This tutorial runs database code against a real container: start the engine, apply the migrations, isolate each test’s data, and tear it down reliably. The examples use a container manager for PostgreSQL, and the approach applies to any database with an official image.

Start the real engine in a container

Run the same database engine and version as production, in a container the test starts and stops. The closest the test database is to production, the more bugs it catches: the same engine catches SQL and type behavior, and the same version catches version-specific features. Pin the version so the tests do not drift with a floating tag.

Start the container once per suite, not per test, because the startup is the expensive part and the tests can share the engine. Wait for the engine to accept connections before running the first test, by polling a readiness check or using the container library’s wait strategy, or the first test races the startup and fails flakily.

import { PostgreSqlContainer } from '@testcontainers/postgresql';
import { afterAll, beforeAll } from 'vitest';

let container, db;
beforeAll(async () => {
  container = await new PostgreSqlContainer('postgres:16').start();  // pinned version
  db = makePool(container.getConnectionUri());
  await migrate(db);            // apply the real migrations to the fresh database
}, 60000);

afterAll(async () => {
  await db.end();
  await container.stop();       // tear down even if a test failed
});

Migrate to the current schema

Apply the project’s migrations to the empty container so the tests run against the current schema, not a hand-built one. Running the migrations also tests them, because a migration that fails or leaves the schema wrong fails the suite before the tests run. This keeps the test schema the same as the production schema, which is what makes the tests meaningful.

A hand-written schema in the test setup drifts from the migrations: a column added to production is missing in the test, and a query that works in tests fails in production. Applying the real migrations removes that drift and turns the migration suite itself into a test. If the migrations are slow, run them once per suite against the shared container.

Isolate each test’s data

Tests that share a database see each other’s rows, so their order matters and one leaves state that breaks another. Isolate by wrapping each test in a transaction that is rolled back at the end, so the rows vanish and the next test starts clean. This is fast and simple for tests that use a single connection, which is most of them.

For tests that span multiple connections or commit explicitly, a transaction rollback does not work, so isolate with a fresh schema per test or by truncating the tables before each test. Choose the method from what the test does: rollback for a single-connection test, truncate or schema-per-test for one that needs to commit or to use concurrent connections.

import { beforeEach, afterEach } from 'vitest';

let tx;
beforeEach(async () => {
  tx = await db.begin();       // a transaction per test
  await tx.setIsolation('READ COMMITTED');
});
afterEach(async () => {
  await tx.rollback();         // discard the rows; the next test starts clean
});
// the code under test uses tx, so its rows never persist

Tear down reliably

Stop the container after the suite, in a hook that runs even when a test failed, or a failed run leaks a container and a port until the next run and the CI fills up. The test framework’s afterAll runs on success and failure, so a stop there is enough; a global teardown that removes any leftover containers is a backstop for a crashed run.

Remove the container, not just stop it, so its state and its port are released. A leaked container holds a port that the next run may need, and on a shared CI machine the leak accumulates. The container library usually labels the containers so a cleanup command can remove the labeled leftovers, which handles the case where the process died before teardown.

# remove any leftover test containers after a crashed run
docker ps -aq --filter "label=testcontainers" | xargs -r docker rm -f
# assert no labeled container remains after the suite

Test migrations and failures, not just the happy path

Because the container applies the real migrations, a failing migration fails the suite, which tests the migrations themselves. Test a unique constraint by inserting a duplicate and asserting the database rejects it, not just that a valid insert works. Test a transaction rollback by inserting, throwing, and asserting the row is absent. These tests exercise the database’s behavior, which the mock could not.

# a constraint test: insert the same unique key twice and expect the second to fail
node -e '
await db.query("INSERT INTO users (email) VALUES ($1)", ["[email protected]"]);
try { await db.query("INSERT INTO users (email) VALUES ($1)", ["[email protected]"]); }
catch (e) { console.log("rejected as expected:", e.code); }
'

Common pitfalls

Mocking the database and testing your assumptions, using a floating image tag so the engine drifts, a hand-written test schema that diverges from the migrations, sharing a database without isolating the rows so tests are order-dependent, and a container that leaks on a failed run are the recurring mistakes. A real pinned container, running the real migrations, per-test isolation, reliable teardown, and a cleanup backstop address them.

Conclusion

Test database code against the real engine, not a mock. Start a pinned container per suite, apply the real migrations so the schema and the migrations are tested, isolate each test’s data with a transaction or a fresh schema, and tear the container down reliably. Self-check by asserting a duplicate insert is rejected and that no container remains after the suite. Then the tests catch the SQL, constraint, and isolation behavior that reaches production.

Sources: Testcontainers, Testcontainers: PostgreSQL module, PostgreSQL: Transaction isolation.

FAQ

Why not mock the database?
A mock tests your code against your assumptions about the database, not against the database. It misses the real SQL semantics, the constraint behavior, the type coercions, and the isolation levels. A real container tests against the actual engine, which is where the bugs are.
Isn't a container slow?
Starting one per suite is a few seconds and is amortized over all the tests in the suite. Starting one per test is slower, so share the container across a suite and isolate the data per test with a transaction or a schema. The reliability is worth the seconds.

Related Examples