Skip to content
jshacks.dev
Testing

Run each test in a transaction and roll back

Wrap every test in a database transaction and roll it back in afterEach, so writes never leak between tests and nothing needs cleaning up.

1 min read
Summarize in AI

Tests that write to a real database either clean up after themselves or poison each other. A transaction per test gives you both isolation and speed, because the rollback undoes everything at once.

tests/helpers/tx.jsJavaScript
import { beforeEach, afterEach } from 'vitest';
import { pool } from './pool.js';

export function useTransaction() {
  const ctx = {};

  beforeEach(async () => {
    ctx.client = await pool.connect();
    await ctx.client.query('BEGIN');
  });

  afterEach(async () => {
    await ctx.client.query('ROLLBACK');
    ctx.client.release();
  });

  return ctx;
}
tests/users.test.jsJavaScript
import { test, expect } from 'vitest';
import { useTransaction } from './helpers/tx.js';

const tx = useTransaction();

test('inserts a user', async () => {
  await tx.client.query("INSERT INTO users (name) VALUES ('Ada')");
  const { rows } = await tx.client.query('SELECT count(*)::int AS n FROM users');
  expect(rows[0].n).toBe(1);
});

test('starts from an empty table', async () => {
  const { rows } = await tx.client.query('SELECT count(*)::int AS n FROM users');
  expect(rows[0].n).toBe(0);
});
Text
 ✓ tests/users.test.js (2 tests)

The second test sees an empty table because the first test's insert was rolled back. Both run on one connection, so the code under test must use ctx.client too, otherwise its writes happen outside the transaction.

This does not work for code that opens its own transaction and commits, since PostgreSQL has no true nested transactions. Savepoints help there, per the PostgreSQL SAVEPOINT docs.

Taggedvitest
Share

More snippets

Debugging

Debug a single Vitest test in VS Code

Run one Vitest file under the VS Code debugger with a launch configuration that passes the open file, so breakpoints in tests and source work. Vitest 3.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.