How-To Guide

How to Test Database Transactions and Rollbacks

Test transaction boundaries, rollback behaviour and isolation with real databases, covering the paths that a mock cannot represent.

On this page

  1. Introduction
  2. Why Mocks Cannot Test Transactions
  3. Testing Rollback on Failure
  4. Isolating Tests with a Transaction Wrapper
  5. Testing Isolation and Concurrency
  6. Testing Constraints and Their Errors
  7. Deterministic Setup and Teardown
  8. Common Pitfalls and Conclusion

Introduction

Transactions are where correctness lives and where bugs hide. A rollback that does not roll back, a partial commit, a lost update under concurrency, a constraint violated only when two transactions overlap: none of these are visible to a unit test with a mocked database, because the mock has no transactional semantics. Testing transactions means running against a real database engine, exercising the boundaries explicitly, and asserting what persists after a failure.

Why Mocks Cannot Test Transactions

A mocked database returns whatever the test tells it to and has no notion of commit, rollback, isolation or locking. It cannot reproduce the behaviour that matters: what happens when a constraint fires mid-transaction, when two transactions touch the same row, or when the process dies before commit. Those are properties of the engine, not of your code, and only the engine can exhibit them.

Use a real database in tests. A lightweight local engine or a containerised one started for the test run gives real transactional semantics with acceptable speed. The mock is fine for testing that your code calls the repository with the right arguments; it is useless for testing that a failed step leaves the database unchanged.

# what a mock cannot show
[ ] rollback actually undoes earlier writes in the transaction
[ ] a constraint violation aborts the whole transaction
[ ] two concurrent transactions conflict or deadlock
[ ] isolation level changes what a concurrent read sees
[ ] a crash before commit leaves nothing partial
# => run these against a real engine (local or containerised)

Testing Rollback on Failure

The core transaction test triggers a failure partway and asserts that nothing from the transaction persists. Arrange a sequence of writes whose later step fails, then query the database directly to confirm that the earlier writes are gone. The assertion must be on database state, not on the absence of an exception.

Cover the failure modes explicitly: a constraint violation, an application-thrown error, a timeout, and a crash simulated by closing the connection mid-transaction. Each should leave the database in its pre-transaction state, and each is a separate test because they exercise different rollback paths.

test('rollback leaves no partial writes on failure', async ({ db }) => {
  await db.query('CREATE TABLE accounts (id serial primary key, balance int not null)');
  await db.query('INSERT INTO accounts (balance) VALUES (100)');

  await expect(db.transaction(async (tx) => {
    await tx.query('UPDATE accounts SET balance = balance - 30 WHERE id = 1');
    await tx.query('INSERT INTO accounts (balance) VALUES (-5)'); // fails a check if any
    throw new Error('later step fails');
  })).rejects.toThrow();

  const { rows } = await db.query('SELECT balance FROM accounts WHERE id = 1');
  expect(rows[0].balance).toBe(100);   // earlier update rolled back
});

Isolating Tests with a Transaction Wrapper

For fast, isolated tests, wrap each test in a transaction and roll it back at the end, so tests that write do not leave data behind and run in any order. This is faster than recreating the schema per test and gives isolation for free, because the rollback discards all writes.

The caveat is that this technique cannot test the transaction boundaries themselves, since the outer wrapper is the only transaction. Use the wrapper for tests of query logic and use explicit transactions for tests of transactional behaviour. Mixing both in one suite is fine as long as you know which technique each test needs.

# two techniques, for two purposes
per-test transaction wrapper:
  BEGIN; ... test writes ...; ROLLBACK
  -> fast, isolated, good for query/logic tests
  -> cannot test commit/rollback semantics (the wrapper IS the tx)

explicit transaction test:
  drive the real transaction boundary, assert on committed state
  -> for rollback, commit, isolation, concurrency behaviour

Testing Isolation and Concurrency

Isolation is invisible until two transactions interact. Open two connections, start transactions in both, and interleave their operations to observe what each sees. At read-committed, one transaction does not see the other’s uncommitted write; at serialisable, a conflict causes one to fail with a serialization error that your code must retry.

Test the concurrency failures your application must handle: a lost update where two transactions read-modify-write the same row, a deadlock where they acquire locks in opposite order, and a serialization failure under serialisable isolation. Each test asserts both what the database does and that your retry logic recovers.

test('lost update prevented by row lock', async ({ pool }) => {
  const a = await pool.connect();
  const b = await pool.connect();
  await a.query('BEGIN'); await b.query('BEGIN');

  await a.query('SELECT balance FROM accounts WHERE id = 1 FOR UPDATE'); // lock
  // B blocks on the same row; drive it and expect it to wait, not to race
  const bLock = b.query('SELECT balance FROM accounts WHERE id = 1 FOR UPDATE');
  await bLock; // resolves only after A commits/releases
  await a.query('COMMIT'); await b.query('COMMIT');

  a.release(); b.release();
});

Testing Constraints and Their Errors

Constraints are part of the contract, and the error the engine raises is what your code must handle. Test each constraint: a unique violation, a foreign key violation, a check violation, a not-null violation. Assert both that the write fails and that your code maps the error to the right response rather than a generic 500.

Also test the transaction-level interaction: a constraint violation inside a transaction must abort the transaction, so the code cannot simply catch the error and continue writing. In PostgreSQL, after an error the transaction is aborted and further statements fail until rollback; the test makes that behaviour explicit and your error handling correct.

test('unique violation maps to a 409, not a 500', async ({ db }) => {
  await db.query('INSERT INTO users (email) VALUES ($1)', ['[email protected]']);
  const res = await handler({ method: 'POST', body: { email: '[email protected]' } });
  expect(res.status).toBe(409);
  // and the first row is unchanged; nothing partial persisted
  const { rows } = await db.query('SELECT count(*)::int AS n FROM users');
  expect(rows[0].n).toBe(1);
});

Deterministic Setup and Teardown

Every transaction test needs a known starting state: the schema, the rows and the constraints. Seed it deterministically before the test and tear it down after, so the test is independent and repeatable. Avoid relying on rows left by another test, which makes the suite order-dependent.

For speed, create the schema once per worker and truncate or roll back data between tests rather than dropping and recreating everything. Containerised databases started once per run amortise startup across the whole suite; per-test container startup is usually too slow. Balance isolation against startup cost, and keep each test’s data its own.

// Setup once per run (container), reset per test (truncate or rollback).
beforeAll(async () => {
  container = await new PostgreSqlContainer().start();
  db = createPool(container.getConnectionUri());
  await migrate(db);                        // schema once
});
beforeEach(async () => {
  await db.query('TRUNCATE accounts RESTART IDENTITY CASCADE');  // known state
});
afterAll(async () => { await db.end(); await container.stop(); });

Common Pitfalls and Conclusion

Do not test transactions with a mock; it has no transactional semantics. Do not assert only that an exception was thrown, without checking the persisted state. Do not wrap rollback tests in a per-test transaction wrapper, or the wrapper is the only transaction measured. Do not skip concurrency tests, which is where lost updates live. And do not accept order-dependent tests, which usually mean a shared database is not isolated.

Transaction correctness is an engine property, so test it against a real engine. Assert what persists after a failure, cover each failure mode and constraint, test isolation and concurrency explicitly, and keep setup deterministic. These tests catch the partial commit and the lost update that a mocked database will happily let through.

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

FAQ

Can I test rollback with a mocked database?
No. A mock has no commit or rollback semantics, so it cannot show what persists after a failure. Test rollback against a real engine and assert on the database state directly, not only on whether an exception was thrown.
How do I keep transaction tests isolated and fast?
Use one container per run and reset data between tests by truncating or by wrapping each test in a transaction you roll back. For tests of the transaction boundary itself, drive an explicit transaction instead of the wrapper, since the wrapper is the only transaction it can measure.

Related Examples