Testcontainers Docker PostgreSQL Integration

Spin up disposable PostgreSQL containers for integration tests with Testcontainers, waiting for readiness and reusing one container per suite.

TypescriptNodeCli Tooling

Code

typescriptsnippet
40 lines
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();
});

How the snippet works

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. PostgreSqlContainer, Pool, afterAll, beforeAll, test are the only symbols borrowed from @testcontainers/postgresql — the coupling is explicit and narrow.

Caveats

  • @testcontainers/postgresql, pg and vitest must be installed first — the snippet imports them directly.

Statements that matter

await container?.stop();
await pool?.end();
const read = await pool.query('SELECT count(*)::int AS n FROM invoices');

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Yes: `@testcontainers/postgresql`, `pg` and `vitest` must be present in the project or the import fails at load time.