Testcontainers Database Patterns: PostgreSQL, MongoDB, and Redis
Database integration tests have three recurring challenges: getting the database into the right state before a test, cleaning up after, and keeping tests fast. This guide covers patterns for PostgreSQL, MongoDB, and Redis with Testcontainers.
PostgreSQL Patterns
Schema Setup with Migrations
Always test against the migrated schema, not a hand-crafted DDL:
// Node.js — using node-pg-migrate
import { PostgreSqlContainer } from '@testcontainers/postgresql';
import { migrate } from 'node-pg-migrate';
import pg from 'pg';
let container: StartedPostgreSqlContainer;
let pool: pg.Pool;
beforeAll(async () => {
container = await new PostgreSqlContainer('postgres:16').start();
pool = new pg.Pool({ connectionString: container.getConnectionUri() });
// Run your real migrations
await migrate({
databaseUrl: container.getConnectionUri(),
dir: 'migrations',
direction: 'up',
migrationsTable: 'pgmigrations',
});
}, 30_000);
afterAll(async () => {
await pool.end();
await container.stop();
});Seed Data Patterns
SQL fixture files:
import { readFileSync } from 'fs';
beforeEach(async () => {
const seed = readFileSync('src/test/fixtures/seed.sql', 'utf-8');
await pool.query(seed);
});
afterEach(async () => {
await pool.query('TRUNCATE TABLE users, orders, products CASCADE');
});-- src/test/fixtures/seed.sql
INSERT INTO users (id, email, name, role) VALUES
(1, 'admin@example.com', 'Admin User', 'admin'),
(2, 'user@example.com', 'Regular User', 'member');
INSERT INTO products (id, name, price, category) VALUES
(1, 'Laptop', 999.99, 'Electronics'),
(2, 'Phone', 699.99, 'Electronics');Programmatic factories:
async function createUser(pool: pg.Pool, overrides = {}) {
const defaults = {
email: `user-${Date.now()}@example.com`,
name: 'Test User',
role: 'member',
};
const data = { ...defaults, ...overrides };
const result = await pool.query(
'INSERT INTO users (email, name, role) VALUES ($1, $2, $3) RETURNING *',
[data.email, data.name, data.role]
);
return result.rows[0];
}
test('admin can list all users', async () => {
await createUser(pool, { role: 'admin', email: 'admin@example.com' });
await createUser(pool, { role: 'member' });
await createUser(pool, { role: 'member' });
const users = await listUsers(pool, { requestingRole: 'admin' });
expect(users).toHaveLength(3);
});Transaction-Based Isolation
The cleanest isolation strategy — no truncation needed:
let client: pg.PoolClient;
beforeEach(async () => {
client = await pool.connect();
await client.query('BEGIN');
});
afterEach(async () => {
await client.query('ROLLBACK');
client.release();
});
// Pass `client` to functions under test, not `pool`
test('creates order with items', async () => {
const order = await createOrder(client, { userId: 1, items: ['prod-1', 'prod-2'] });
const items = await getOrderItems(client, order.id);
expect(items).toHaveLength(2);
});This requires your application code to accept a connection/client parameter, not hard-code a pool. A small coupling cost for perfect test isolation.
Testing Constraints and Errors
Real PostgreSQL enforces constraints. Test them:
test('rejects duplicate email', async () => {
await pool.query("INSERT INTO users (email) VALUES ('dup@example.com')");
await expect(
pool.query("INSERT INTO users (email) VALUES ('dup@example.com')")
).rejects.toThrow('duplicate key value violates unique constraint');
});
test('rejects negative price', async () => {
await expect(
pool.query('INSERT INTO products (name, price) VALUES ($1, $2)', ['Item', -10])
).rejects.toThrow('violates check constraint');
});These tests catch constraint definitions in your migrations — something H2 in compatibility mode would silently allow.
Full-Text Search Testing
test('searches products by keyword', async () => {
await pool.query(`
INSERT INTO products (name, description) VALUES
('PostgreSQL Guide', 'A complete guide to PostgreSQL database'),
('Redis in Action', 'Practical Redis patterns for developers')
`);
const results = await pool.query(`
SELECT name FROM products
WHERE to_tsvector('english', name || ' ' || description) @@ plainto_tsquery('english', 'postgresql')
`);
expect(results.rows).toHaveLength(1);
expect(results.rows[0].name).toBe('PostgreSQL Guide');
});MongoDB Patterns
Setup
import { MongoDBContainer } from '@testcontainers/mongodb';
import { MongoClient, Db } from 'mongodb';
let container: StartedMongoDBContainer;
let client: MongoClient;
let db: Db;
beforeAll(async () => {
container = await new MongoDBContainer('mongo:7').start();
client = new MongoClient(container.getConnectionString());
await client.connect();
db = client.db('testdb');
}, 30_000);
afterAll(async () => {
await client.close();
await container.stop();
});
afterEach(async () => {
// Drop all collections between tests
const collections = await db.listCollections().toArray();
await Promise.all(collections.map(c => db.collection(c.name).drop()));
});Index Testing
test('query uses index for email lookup', async () => {
const collection = db.collection('users');
await collection.createIndex({ email: 1 }, { unique: true });
// Insert test data
await collection.insertMany([
{ email: 'alice@example.com', name: 'Alice' },
{ email: 'bob@example.com', name: 'Bob' },
]);
// Use explain to verify index usage
const plan = await collection.find({ email: 'alice@example.com' }).explain('executionStats');
expect(plan.executionStats.executionStages.stage).toBe('IXSCAN');
});
test('rejects duplicate email', async () => {
const collection = db.collection('users');
await collection.createIndex({ email: 1 }, { unique: true });
await collection.insertOne({ email: 'dup@example.com' });
await expect(
collection.insertOne({ email: 'dup@example.com' })
).rejects.toThrow(/duplicate key/);
});Aggregation Pipeline Testing
test('calculates order totals by user', async () => {
const orders = db.collection('orders');
await orders.insertMany([
{ userId: 'user1', amount: 100 },
{ userId: 'user1', amount: 50 },
{ userId: 'user2', amount: 200 },
]);
const result = await orders.aggregate([
{ $group: { _id: '$userId', total: { $sum: '$amount' } } },
{ $sort: { total: -1 } },
]).toArray();
expect(result[0]).toEqual({ _id: 'user2', total: 200 });
expect(result[1]).toEqual({ _id: 'user1', total: 150 });
});Redis Patterns
Setup
import { RedisContainer } from '@testcontainers/redis';
import { createClient, RedisClientType } from 'redis';
let container: StartedRedisContainer;
let redisClient: RedisClientType;
beforeAll(async () => {
container = await new RedisContainer('redis:7-alpine').start();
redisClient = createClient({ url: container.getConnectionUrl() });
await redisClient.connect();
}, 30_000);
afterAll(async () => {
await redisClient.disconnect();
await container.stop();
});
afterEach(async () => {
await redisClient.flushAll(); // Clear all keys between tests
});Cache Behavior Testing
test('caches user data with TTL', async () => {
const cache = new UserCache(redisClient);
await cache.set('user:1', { name: 'Alice' }, { ttl: 60 });
const cached = await cache.get('user:1');
expect(cached).toEqual({ name: 'Alice' });
// Verify TTL is set
const ttl = await redisClient.ttl('user:1');
expect(ttl).toBeGreaterThan(0);
expect(ttl).toBeLessThanOrEqual(60);
});
test('returns null for expired keys', async () => {
await redisClient.set('temp-key', 'value', { EX: 1 }); // 1 second TTL
// In real tests, use fake timers or set very short TTLs and wait
await new Promise(resolve => setTimeout(resolve, 1100));
const value = await redisClient.get('temp-key');
expect(value).toBeNull();
});Pub/Sub Testing
test('publishes and receives messages', async () => {
const subscriber = redisClient.duplicate();
await subscriber.connect();
const received: string[] = [];
await subscriber.subscribe('events', message => {
received.push(message);
});
// Publish from a different client
await redisClient.publish('events', JSON.stringify({ type: 'order.created', id: '123' }));
// Wait for message delivery
await new Promise(resolve => setTimeout(resolve, 100));
expect(received).toHaveLength(1);
expect(JSON.parse(received[0])).toEqual({ type: 'order.created', id: '123' });
await subscriber.unsubscribe('events');
await subscriber.disconnect();
});Rate Limiting Testing
test('enforces rate limit', async () => {
const limiter = new RedisRateLimiter(redisClient, { limit: 3, window: 60 });
expect(await limiter.check('user:1')).toBe(true); // 1st request
expect(await limiter.check('user:1')).toBe(true); // 2nd request
expect(await limiter.check('user:1')).toBe(true); // 3rd request
expect(await limiter.check('user:1')).toBe(false); // 4th request — blocked
});Multi-Database Test Setup
Test a service that uses PostgreSQL + Redis together:
import { PostgreSqlContainer } from '@testcontainers/postgresql';
import { RedisContainer } from '@testcontainers/redis';
let postgres: StartedPostgreSqlContainer;
let redis: StartedRedisContainer;
beforeAll(async () => {
[postgres, redis] = await Promise.all([
new PostgreSqlContainer('postgres:16').start(),
new RedisContainer('redis:7-alpine').start(),
]);
// Set env vars for your app
process.env.DATABASE_URL = postgres.getConnectionUri();
process.env.REDIS_URL = redis.getConnectionUrl();
await runMigrations(postgres.getConnectionUri());
}, 60_000);
afterAll(async () => {
await Promise.all([postgres.stop(), redis.stop()]);
});Starting containers in parallel with Promise.all cuts setup time roughly in half.
Summary
Key patterns across all databases:
| Concern | PostgreSQL | MongoDB | Redis |
|---|---|---|---|
| State cleanup | TRUNCATE CASCADE or transaction rollback |
Drop collections | FLUSHALL |
| Seed data | SQL files or factory functions | insertMany |
SET / HSET |
| Constraint testing | Assert on error message | Assert on duplicate key error |
TTL assertions |
| Schema setup | Run real migrations | Create indexes explicitly | N/A |
| Parallel setup | Yes, via Promise.all |
Yes | Yes |
Real containers catch real bugs. The startup cost (3–15 seconds per suite) is worth the confidence you get from testing against the actual database engine.