Write integration tests with proper setup/teardown
✓Works with OpenClaudeYou are a testing expert specializing in integration tests. The user wants to write integration tests with proper setup/teardown sequences that test multiple components working together.
What to check first
- Run
npm list jest @testing-library/reactto verify test framework and dependencies are installed - Check if you have a test database or mock server configured in your project root (e.g.,
.env.test)
Steps
- Create a test file with
.test.jsor.integration.test.jsextension in your__tests__ortestsdirectory - Import
beforeAll,afterAll,beforeEach,afterEachfrom Jest at the top of the file - Set up database connection or mock server in
beforeAllhook — this runs once before all tests - Initialize test data fixtures in
beforeEachhook — this runs before each individual test - Write each test as an independent scenario that uses the fixtures and verifies component interactions
- Clean up test data in
afterEachhook — this prevents test pollution and isolation issues - Tear down database connections or close server in
afterAllhook — this runs once after all tests complete - Run tests with
npm test -- --testPathPattern=integrationto verify setup/teardown executes correctly
Code
const request = require('supertest');
const { Database } = require('pg');
const app = require('../app');
let db;
let testUserId;
let testProjectId;
beforeAll(async () => {
// Initialize test database connection once for all tests
db = new Database({
connectionString: process.env.TEST_DATABASE_URL,
});
await db.connect();
// Create test schema or tables
await db.query(`CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
email VARCHAR(255),
created_at TIMESTAMP DEFAULT NOW()
)`);
});
afterAll(async () => {
// Tear down: close database connection
if (db) {
await db.query('DROP TABLE IF EXISTS users CASCADE');
await db.end();
}
});
beforeEach(async () => {
// Reset state before each test: insert fresh test data
const userResult = await db.query(
'INSERT INTO users (email) VALUES ($1) RETURNING id',
['test@example.com']
);
testUserId = userResult.rows[0].id;
});
afterEach(async () => {
// Clean up: remove test data after each test
await db.query('DELETE FROM users WHERE id = $1', [testUserId]);
});
describe('User API Integration', () => {
test('should create user and retrieve it', async () => {
const response = await request(app)
.get(`/api/users/${testUserId}`)
.expect(200);
expect(response.body.email).toBe('test@example.com');
});
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Testing Skills
Other Claude Code skills in the same category — free to download.
Unit Test Generator
Generate unit tests for any function or class
Test Coverage Analyzer
Analyze test coverage gaps and suggest tests to write
Mock Generator
Generate mocks, stubs, and fakes for dependencies
Snapshot Test Creator
Create snapshot tests for UI components
E2E Test Writer
Write end-to-end tests using Playwright or Cypress
Test Data Factory
Create test data factories and fixtures
API Test Suite
Generate API test suites for REST endpoints
Mutation Testing Setup
Set up mutation testing to verify test quality
Want a Testing skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.