Testcontainers for Node.js: Integration Testing with Real Services

Testcontainers for Node.js: Integration Testing with Real Services

Testcontainers has a Node.js implementation (testcontainers npm package) that works with Jest, Vitest, and any other test runner. You get the same benefits as the Java version: real Docker containers, automatic lifecycle management, and dynamic port binding.

Installation

npm install -D testcontainers

Requires Docker running on the host (or accessible via DOCKER_HOST).

Basic Usage

import { PostgreSqlContainer } from '@testcontainers/postgresql';

describe('UserRepository', () => {
  let container: StartedPostgreSqlContainer;
  let pool: pg.Pool;

  beforeAll(async () => {
    container = await new PostgreSqlContainer('postgres:16')
      .withDatabase('testdb')
      .withUsername('test')
      .withPassword('test')
      .start();

    pool = new pg.Pool({
      connectionString: container.getConnectionUri(),
    });

    await runMigrations(pool);
  }, 60_000); // Give Docker time to pull the image

  afterAll(async () => {
    await pool.end();
    await container.stop();
  });

  test('saves and retrieves a user', async () => {
    await pool.query("INSERT INTO users (email, name) VALUES ('alice@example.com', 'Alice')");
    const result = await pool.query("SELECT * FROM users WHERE email = 'alice@example.com'");
    
    expect(result.rows).toHaveLength(1);
    expect(result.rows[0].name).toBe('Alice');
  });
});

Available Modules

Install individual modules for type-safe container configuration:

npm install -D @testcontainers/postgresql
npm install -D @testcontainers/mongodb
npm install -D @testcontainers/redis
npm install -D @testcontainers/kafka
npm install -D @testcontainers/mysql
npm install -D @testcontainers/rabbitmq
npm install -D @testcontainers/elasticsearch

Each module provides a typed container class with service-specific methods:

import { RedisContainer } from '@testcontainers/redis';

const redis = await new RedisContainer('redis:7-alpine').start();
const client = createClient({ url: redis.getConnectionUrl() });
import { MongoDBContainer } from '@testcontainers/mongodb';

const mongo = await new MongoDBContainer('mongo:7').start();
const client = new MongoClient(mongo.getConnectionString());

Generic Container

For services without a module:

import { GenericContainer, Wait } from 'testcontainers';

const container = await new GenericContainer('minio/minio')
  .withExposedPorts(9000)
  .withEnvironment({
    MINIO_ROOT_USER: 'minioadmin',
    MINIO_ROOT_PASSWORD: 'minioadmin',
  })
  .withCommand(['server', '/data'])
  .withWaitStrategy(Wait.forHttp('/minio/health/live', 9000))
  .start();

const port = container.getMappedPort(9000);
const endpoint = `http://localhost:${port}`;

Wait Strategies

import { Wait } from 'testcontainers';

// Wait for log message
.withWaitStrategy(Wait.forLogMessage(/ready to accept connections/))

// Wait for port
.withWaitStrategy(Wait.forListeningPort())

// Wait for HTTP health check
.withWaitStrategy(Wait.forHttp('/health', 8080).forStatusCode(200))

// Wait for successful shell command
.withWaitStrategy(Wait.forSuccessfulCommand('redis-cli ping'))

// Combine strategies
.withWaitStrategy(Wait.forAll([
  Wait.forListeningPort(),
  Wait.forLogMessage(/started/),
]))

Vitest Integration

Vitest's global setup hooks are ideal for container lifecycle:

// vitest.config.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globalSetup: './src/test/global-setup.ts',
  },
});
// src/test/global-setup.ts
import { PostgreSqlContainer, StartedPostgreSqlContainer } from '@testcontainers/postgresql';

let container: StartedPostgreSqlContainer;

export async function setup() {
  container = await new PostgreSqlContainer('postgres:16').start();
  
  process.env.DATABASE_URL = container.getConnectionUri();
  
  // Run migrations
  await migrate(container.getConnectionUri());
}

export async function teardown() {
  await container?.stop();
}
// src/repositories/__tests__/user.test.ts
import { createPool } from '../db';

test('finds user by email', async () => {
  // process.env.DATABASE_URL is set by globalSetup
  const pool = createPool(process.env.DATABASE_URL!);
  
  await pool.query("INSERT INTO users (email) VALUES ('test@example.com')");
  const user = await findUserByEmail(pool, 'test@example.com');
  
  expect(user).toBeDefined();
  expect(user!.email).toBe('test@example.com');
  
  await pool.end();
});

Jest Integration

For Jest, use globalSetup and globalTeardown:

// jest.config.ts
export default {
  globalSetup: './src/test/jest-global-setup.ts',
  globalTeardown: './src/test/jest-global-teardown.ts',
};
// src/test/jest-global-setup.ts
import { PostgreSqlContainer } from '@testcontainers/postgresql';

module.exports = async () => {
  const container = await new PostgreSqlContainer('postgres:16').start();
  
  process.env.DATABASE_URL = container.getConnectionUri();
  
  // Store container reference for teardown
  (global as any).__TESTCONTAINERS_POSTGRES__ = container;
};
// src/test/jest-global-teardown.ts
module.exports = async () => {
  const container = (global as any).__TESTCONTAINERS_POSTGRES__;
  if (container) {
    await container.stop();
  }
};

Database Cleanup Between Tests

Tests need a clean database state. Options:

Truncate tables (fast, works with all databases):

afterEach(async () => {
  await pool.query('TRUNCATE TABLE users, orders, products CASCADE');
});

Drop and recreate (clean but slower):

afterEach(async () => {
  await pool.query('DROP SCHEMA public CASCADE; CREATE SCHEMA public;');
  await runMigrations(pool);
});

Use transactions (fastest, requires database support):

let client: pg.PoolClient;

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

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

test('creates user', async () => {
  await client.query("INSERT INTO users (email) VALUES ('test@example.com')");
  const result = await client.query('SELECT COUNT(*) FROM users');
  expect(result.rows[0].count).toBe('1');
  // Rolls back after test — next test starts clean
});

Multiple Containers with a Network

When your service depends on multiple services:

import { Network } from 'testcontainers';

let network: StartedNetwork;
let postgres: StartedPostgreSqlContainer;
let redis: StartedGenericContainer;

beforeAll(async () => {
  network = await new Network().start();

  postgres = await new PostgreSqlContainer('postgres:16')
    .withNetwork(network)
    .withNetworkAliases('db')
    .start();

  redis = await new GenericContainer('redis:7-alpine')
    .withNetwork(network)
    .withExposedPorts(6379)
    .start();

  // Your service can connect to "db:5432" and "redis:6379" within the network
}, 60_000);

afterAll(async () => {
  await redis.stop();
  await postgres.stop();
  await network.stop();
});

Environment Variables for Container Connection

A common pattern: set env vars in setup, read them in your app code:

// global-setup.ts
const container = await new PostgreSqlContainer('postgres:16').start();

process.env.PGHOST = container.getHost();
process.env.PGPORT = String(container.getMappedPort(5432));
process.env.PGDATABASE = container.getDatabase();
process.env.PGUSER = container.getUsername();
process.env.PGPASSWORD = container.getPassword();

Your application code reads from environment variables as usual — no test-specific code paths needed.

Timeout Configuration

Image pulls can be slow. Configure timeouts appropriately:

// Jest
jest.setTimeout(60_000); // 60 seconds for container startup

// Vitest per-test
test('...', async () => { ... }, { timeout: 60_000 });

// Vitest global
export default defineConfig({
  test: {
    testTimeout: 60_000,
    hookTimeout: 60_000,
  },
});

Pre-pull images in CI to reduce startup time:

# .github/workflows/ci.yml
- name: Pre-pull images
  run: |
    docker pull postgres:16
    docker pull redis:7-alpine

Logging

Enable Testcontainers debug logging to diagnose startup issues:

DEBUG=testcontainers* npm test

Or per-container:

const container = await new PostgreSqlContainer('postgres:16')
  .withLogConsumer(stream => {
    stream.on('data', line => console.log(line));
    stream.on('err', line => console.error(line));
  })
  .start();

Summary

Testcontainers for Node.js fits naturally into Jest and Vitest:

  1. Use module-specific containers (@testcontainers/postgresql, etc.) for typed APIs
  2. Use globalSetup/globalTeardown (Jest) or globalSetup (Vitest) for one-time container startup
  3. Clean state between tests with TRUNCATE or transactions
  4. Pre-pull Docker images in CI to keep startup fast
  5. Set testTimeout to at least 60 seconds — container pulls take time on first run

The tradeoff vs mocks: slower test startup, but honest tests that catch real database behavior.

Read more

Start now free