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.
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.
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;
}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);
}); ✓ 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.