Testcontainers Docker PostgreSQL Integration
Spin up disposable PostgreSQL containers for integration tests with Testcontainers, waiting for readiness and reusing one container per suite.
Code
import { PostgreSqlContainer } from '@testcontainers/postgresql';
import { Pool } from 'pg';
import { afterAll, beforeAll, test } from 'vitest';
let container;
let pool: Pool;
beforeAll(async () => {
container = await new PostgreSqlContainer('postgres:16-alpine')
.withDatabase('app_test')
.withUsername('tester')
.withPassword('secret')
.withCommand(['postgres', '-c', 'fsync=off'])
.start();
pool = new Pool({ connectionString: container.getConnectionUri() });
await pool.query(`
CREATE TABLE invoices (
id SERIAL PRIMARY KEY,
total_cents INTEGER NOT NULL CHECK (total_cents >= 0)
)
`);
}, 120_000);
test('insert and read back within a real postgres engine', async () => {
const inserted = await pool.query(
'INSERT INTO invoices (total_cents) VALUES ($1) RETURNING id, total_cents',
[1999],
);
expect(inserted.rows[0].total_cents).toBe(1999);
const read = await pool.query('SELECT count(*)::int AS n FROM invoices');
expect(read.rows[0].n).toBe(1);
});
afterAll(async () => {
await pool?.end();
await container?.stop();
});Report a problem with this exampleOpens a pre-filled issue on GitHub.