Integration tests verificam API completa: routers, controllers, database. Mais lentos que unitários mas detectam bugs reais.
Conceitos Principais
Test Database
DB separado para testes. SQLite in-memory ou Docker container. Seed data antes, cleanup depois.
Supertest
HTTP assertions. request(app).get("/users"). Testa rotas Express/Fastify. Status, headers, body.
Test Fixtures
Dados pré-definidos. Users, posts, orders. Consistente entre testes. Factory functions.
Auth Testing
Login antes de teste. JWT token em headers. Testa rotas protegidas. Roles e permissions.
Passo a Passo
- Setup Test DB: Crie database_test. Migrations automáticas. beforeAll conecta, afterAll desconecta. afterEach limpa dados.
- Supertest Básico: const res = await request(app).get("/users").expect(200); expect(res.body).toHaveLength(3);
- Seed Data: beforeEach async: await db.users.create([user1, user2]). Dados consistentes. Factory: createUser({ name: "John" }).
- Test Auth Routes: POST /login, capture token. GET /profile com Authorization header. Teste 401 sem token.
- CI Integration: GitHub Actions: docker-compose up db-test. Migrations. Run tests. docker-compose down.
Boas Praticas
Recomendacoes
• Database isolado para testes
• Seed data antes, cleanup depois
• Teste fluxos completos (CRUD)
• Assert status codes e body
• Teste casos de erro (400, 401, 404)
• Auth em testes protegidos
Erros Comuns
Evite estes erros
• Usar database de produção
• Não fazer cleanup (dados vazam)
• Testar apenas happy path
• Testes dependentes de ordem
• Não testar autorização
Checklist
- Test database configurado
- Supertest instalado
- Seed/cleanup funcionando
- Auth testada
- Error cases cobertos
- CI rodando integration tests