This example shows how to use Testcontainers to run integration tests against a real PostgreSQL database without any manual setup.
- Node.js 18+
- Docker (must be running — no manual container setup needed)
Install dependencies:
npm install
npm install @testcontainers/postgresqlnpm testDocker does not need to be touched manually. Testcontainers automatically
pulls, starts, and stops the PostgreSQL container when you run npm test.
- Testcontainers pulls a
postgres:14Docker image (first run only) - A real PostgreSQL container starts automatically
- The tests run against the real database
- The container is stopped and removed when tests finish
PostgreSqlContainer is not bundled with the core testcontainers package
in version 10+. It must be installed as a separate scoped package:
npm install @testcontainers/postgresqlAnd imported in your test file as:
const { PostgreSqlContainer } = require("@testcontainers/postgresql");Using require("testcontainers") alone will result in a
PostgreSqlContainer is not a constructor error.
userRepository.js— the module being tested (DatabaseLayer)userRepository.test.js— integration tests using Testcontainers
Without Testcontainers you would need to either:
- Mock the database (not a true integration test), or
- Maintain a shared dev database (flaky, slow, hard to reset)
Testcontainers gives you a real database that is:
- Isolated per test run
- Automatically cleaned up
- Identical across all developer machines and CI/CD