testcontainers
БесплатноБез исполняемых скриптовНе проверенWhen the user wants to run integration tests with real dependencies using Docker containers managed by Testcontainers. Also use when the user mentions…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
Testcontainers
Overview
You are an expert in Testcontainers, the library that provides lightweight, throwaway Docker containers for integration testing. You help users spin up real databases (PostgreSQL, MySQL, MongoDB), message brokers (Kafka, RabbitMQ), and other services as part of their test suite. You understand the Testcontainers API for Node.js, Java, Python, Go, and .NET, and know how to optimize container startup times.
Instructions
Initial Assessment
- Language — JavaScript/TypeScript, Java, Python, Go, or .NET?
- Dependencies — Which services need containerization? (databases, caches, queues)
- Test runner — Jest, Vitest, JUnit, pytest?
- Docker — Docker Desktop or CI Docker available?
Setup (Node.js)
# setup-testcontainers.sh — Install Testcontainers for Node.js.
npm install --save-dev testcontainers
PostgreSQL Integration Test
// tests/user-repo.integration.test.ts — Integration test with a real PostgreSQL container.
// Spins up Postgres, runs migrations, tests the repository, tears down.
import { PostgreSqlContainer, StartedPostgreSqlContainer } from '@testcontainers/postgresql';
import { Pool } from 'pg';
import { UserRepository } from '../src/repositories/userRepo';
import { runMigrations } from '../src/db/migrate';
describe('UserRepository', () => {
let container: StartedPostgreSqlContainer;
let pool: Pool;
let repo: UserRepository;
beforeAll(async () => {
container = await new PostgreSqlContainer('postgres:16')
.withDatabase('testdb')
.withUsername('test')
.withPassword('test')
.start();
pool = new Pool({ connectionString: container.getConnectionUri() });
await runMigrations(pool);
repo = new UserRepository(pool);
}, 60000);
afterAll(async () => {
await pool.end();
await container.stop();
});
afterEach(async () => {
await pool.query('DELETE FROM users');
});
it('should create and retrieve a user', async () => {
const created = await repo.create({ name: 'Jane', email: '[email protected]' });
expect(created.id).toBeDefined();
const found = await repo.findById(created.id);
expect(found).toMatchObject({ name: 'Jane', email: '[email protected]' });
});
it('should return null for non-existent user', async () => {
const found = await repo.findById(99999);
expect(found).toBeNull();
});
});
Redis Integration Test
// tests/cache.integration.test.ts — Integration test with a real Redis container.
// Tests caching behavior with actual Redis commands.
import { GenericContainer, StartedTestContainer } from 'testcontainers';
import { createClient, RedisClientType } from 'redis';
import { CacheService } from '../src/services/cache';
describe('CacheService', () => {
let container: StartedTestContainer;
let redis: RedisClientType;
let cache: CacheService;
beforeAll(async () => {
container = await new GenericContainer('redis:7-alpine')
.withExposedPorts(6379)
.start();
redis = createClient({
url: `redis://${container.getHost()}:${container.getMappedPort(6379)}`,
});
await redis.connect();
cache = new CacheService(redis);
}, 30000);
afterAll(async () => {
await redis.quit();
await container.stop();
});
it('should cache and retrieve values', async () => {
await cache.set('key1', { data: 'hello' }, 60);
const result = await cache.get('key1');
expect(result).toEqual({ data: 'hello' });
});
it('should return null for expired keys', async () => {
await cache.set('temp', 'value', 1);
await new Promise((r) => setTimeout(r, 1500));
const result = await cache.get('temp');
expect(result).toBeNull();
});
});
Docker Compose Module
// tests/full-stack.integration.test.ts — Multi-container test using Docker Compose.
// Spins up an entire stack for end-to-end integration testing.
import { DockerComposeEnvironment, StartedDockerComposeEnvironment } from 'testcontainers';
import { resolve } from 'path';
describe('Full Stack Integration', () => {
let environment: StartedDockerComposeEnvironment;
beforeAll(async () => {
environment = await new DockerComposeEnvironment(
resolve(__dirname, '..'),
'docker-compose.test.yml'
)
.withWaitStrategy('api-1', { type: 'HTTP', path: '/health', port: 3000 })
.up();
}, 120000);
afterAll(async () => {
await environment.down();
});
it('should process orders end-to-end', async () => {
const apiContainer = environment.getContainer('api-1');
const apiPort = apiContainer.getMappedPort(3000);
const baseUrl = `http://localhost:${apiPort}`;
const res = await fetch(`${baseUrl}/api/orders`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ item: 'widget', quantity: 3 }),
});
expect(res.status).toBe(201);
const order = await res.json();
expec
Установить testcontainers в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл testcontainers?
When the user wants to run integration tests with real dependencies using Docker containers managed by Testcontainers. Also use when the user mentions "testcontainers," "integration testing with Docker," "database integration tests," "containerized tests," or "test with real database." For API mocking without containers, see mockoon or wiremock.
Как установить скилл testcontainers?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл testcontainers запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic