Testingintermediate
Write integration tests with proper setup/teardown
Integration Test Writer
Write integration tests with proper setup/teardown
Write integration tests with proper setup/teardown.
Instructions
- Integration tests hit real infrastructure (DB, API, filesystem):
import { createTestDatabase, destroyTestDatabase } from './helpers';
import { UserRepository } from '../src/repositories/user';
let db: TestDatabase;
let repo: UserRepository;
beforeAll(async () => {
db = await createTestDatabase(); // spin up test DB
repo = new UserRepository(db.connection);
});
afterAll(async () => {
await destroyTestDatabase(db); // clean up
});
beforeEach(async () => {
await db.truncateAll(); // clean state per test
});
describe('UserRepository', () => {
it('should save and retrieve user', async () => {
await repo.create({ name: 'Alice', email: 'alice@test.com' });
const user = await repo.findByEmail('alice@test.com');
expect(user).not.toBeNull();
expect(user!.name).toBe('Alice');
});
it('should enforce unique email constraint', async () => {
await repo.create({ name: 'Alice', email: 'alice@test.com' });
await expect(
repo.create({ name: 'Bob', email: 'alice@test.com' })
).rejects.toThrow('duplicate');
});
});
Rules
- Use a separate test database — never test against dev/staging
- Truncate tables between tests, not between suites (isolation)
- Set a timeout: integration tests can be slow
- Run separately from unit tests:
npm run test:integration