Integration testing Node.js with Testcontainers

By

Updated

Tagged: Node.js

Write Node.js integration tests against a real PostgreSQL database with Testcontainers, including schema setup, isolation, cleanup, and CI.

A database mock can confirm your code called a function, but it can’t tell you if your SQL query works in PostgreSQL. PostgreSQL has real types, constraints, transactions, extensions, and query behavior that a fake client won’t catch. If you want database integration tests you can trust, run them against PostgreSQL itself.

That’s what Testcontainers is for. It spins up a temporary container for your test run, hands your code the connection details, and tears the container down when the tests finish.

In this tutorial we’ll test a small books repository against a real PostgreSQL instance so every run gets a fresh database from scratch.

What you need

Before we start, make sure you have:

Start by creating the project:

mkdir books-testcontainers
cd books-testcontainers
npm init -y
npm install pg
npm install --save-dev vitest @testcontainers/postgresql

Next, add "type": "module" and a test script to package.json:

{
  "type": "module",
  "scripts": {
    "test": "vitest run"
  }
}

Write the code we want to test

Create src/books.js with a small books repository:

export function createBooksRepository(client) {
  return {
    async create({ title, author }) {
      const result = await client.query(
        `
          INSERT INTO books (title, author)
          VALUES ($1, $2)
          RETURNING id, title, author
        `,
        [title, author]
      )

      return result.rows[0]
    },

    async findByAuthor(author) {
      const result = await client.query(
        `
          SELECT id, title, author
          FROM books
          WHERE author = $1
          ORDER BY id
        `,
        [author]
      )

      return result.rows
    },
  }
}

Notice that the repository takes a database client as an argument instead of creating its own. That small choice makes it easy to pass in your real connection in production and a Testcontainers connection in tests.

The $1 and $2 placeholders keep values separate from the SQL string. Never build queries by concatenating untrusted input.

Start PostgreSQL in the test

Now create src/books.test.js to start PostgreSQL before the suite runs:

import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'vitest'
import { PostgreSqlContainer } from '@testcontainers/postgresql'
import pg from 'pg'
import { createBooksRepository } from './books.js'

const { Client } = pg

let container
let client
let books

beforeAll(async () => {
  container = await new PostgreSqlContainer('postgres:18-alpine').start()

  client = new Client({
    connectionString: container.getConnectionUri(),
  })

  await client.connect()

  await client.query(`
    CREATE TABLE books (
      id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
      title TEXT NOT NULL,
      author TEXT NOT NULL
    )
  `)

  books = createBooksRepository(client)
}, 60_000)

afterAll(async () => {
  try {
    await client?.end()
  } finally {
    await container?.stop()
  }
})

When that setup runs, Testcontainers handles four things:

  1. It asks your container runtime to start postgres:18-alpine.
  2. It waits until PostgreSQL is ready to accept connections.
  3. It maps the container port to an open port on your machine.
  4. It gives you back the real connection URI.

Don’t hardcode port 5432. Testcontainers picks a dynamic host port on purpose so separate test runs don’t collide. Keep the longer startup timeout too, since Docker might need to download the image on the first run, and pin an explicit image version instead of latest so your tests don’t break when an image updates underneath you.

Write the first integration test

Add your first test case right below the setup hooks:

describe('books repository', () => {
  beforeEach(async () => {
    await client.query(
      'TRUNCATE TABLE books RESTART IDENTITY CASCADE'
    )
  })

  test('creates and finds books by author', async () => {
    await books.create({
      title: 'The Hobbit',
      author: 'J. R. R. Tolkien',
    })

    await books.create({
      title: 'The Silmarillion',
      author: 'J. R. R. Tolkien',
    })

    await books.create({
      title: 'Dune',
      author: 'Frank Herbert',
    })

    const result = await books.findByAuthor('J. R. R. Tolkien')

    expect(result).toEqual([
      {
        id: 1,
        title: 'The Hobbit',
        author: 'J. R. R. Tolkien',
      },
      {
        id: 2,
        title: 'The Silmarillion',
        author: 'J. R. R. Tolkien',
      },
    ])
  })
})

Then run the suite:

npm test

Now you’re running a real integration test, with Node sending SQL over a real database connection. If your syntax, parameter types, constraints, or ordering are wrong, the test fails for the exact same reason production would.

Test database constraints

Database constraints are part of how your app behaves, so it’s worth testing them directly. Add this test to check a not-null constraint:

test('rejects a book without an author', async () => {
  await expect(
    client.query(
      `
        INSERT INTO books (title, author)
        VALUES ($1, $2)
      `,
      ['The Hobbit', null]
    )
  ).rejects.toMatchObject({
    code: '23502',
  })
})

PostgreSQL returns error code 23502 for a not-null violation. Asserting on that code is more reliable than matching the full English error message.

Use real migrations

An inline CREATE TABLE inside your test file works for a quick example, but it’ll drift out of sync as soon as production uses a separate migration system. Instead, run the exact same migrations in your tests that you deploy to production:

beforeAll(async () => {
  container = await new PostgreSqlContainer('postgres:18-alpine').start()
  process.env.DATABASE_URL = container.getConnectionUri()

  await runMigrations({
    connectionString: process.env.DATABASE_URL,
  })

  client = new Client({
    connectionString: process.env.DATABASE_URL,
  })

  await client.connect()
  books = createBooksRepository(client)
})

Doing this catches broken migration ordering, unsupported SQL, and hidden assumptions left over from an old local database. You also verify that an empty database can migrate all the way to your current schema.

Choose an isolation strategy

Your tests shouldn’t depend on the order they run in. For a small suite, truncating the tables you touch before each test is usually enough:

TRUNCATE TABLE books RESTART IDENTITY CASCADE

As your suite grows, you have a few other options:

Rolling back transactions is fast, though it won’t work if your tests open multiple independent connections or commit on purpose. Starting a new container for every single test isolates everything completely, but it gets slow quickly.

A solid default for most projects is one container per test file, running your real migrations once at startup, and cleaning up the changed tables before each test.

Test failures and cleanup

Always close the database client before stopping the container. Using optional chaining keeps teardown from crashing if setup failed halfway through, and a finally block makes sure the container still stops even if closing the client throws an error:

afterAll(async () => {
  try {
    await client?.end()
  } finally {
    await container?.stop()
  }
})

Testcontainers runs a resource reaper in the background to clean up containers if a process dies, so you won’t leave containers behind forever. Even so, closing everything yourself frees resources right away and keeps the cleanup lifecycle clear.

If a test run hangs instead of exiting, look at the usual suspects:

When you can’t tell where a run is stuck, turn on Testcontainers logging to see runtime discovery, image pulls, port mappings, and wait checks.

Run in CI

Standard GitHub-hosted Linux runners already have Docker installed, so your workflow file stays simple:

name: test

on:
  pull_request:
  push:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v7

      - uses: actions/setup-node@v7
        with:
          node-version: 24
          cache: npm

      - run: npm ci
      - run: npm test

You don’t need a separate PostgreSQL service block in your CI config because the test suite starts its own container and picks the exact image version. If you’re on another CI platform, make sure your build jobs have access to a supported Docker-compatible runtime.

What should use Testcontainers?

Reach for Testcontainers anywhere a mock is likely to diverge from how the real service behaves:

Don’t replace all your unit tests with container tests, though. Keep fast unit tests for pure business logic (the built-in Node.js test runner works fine there too), and use a smaller container-backed integration suite for the boundaries where your code talks to a real service.

Want me to talk about your product? You can sponsor this site.

Related posts about node: