Skip to contentPedro Farbo
Lesson 18 / 2550 min

Integration Testing

Integration Testing

Test API routes with Supertest.

Setup

bash
npm install -D supertest @types/supertest

Test Setup

typescript
// src/tests/setup.tsimport { prisma } from '../config/database'; beforeAll(async () => {  await prisma.$executeRaw`TRUNCATE TABLE "User", "Product" CASCADE`;}); afterAll(async () => {  await prisma.$disconnect();});

Testing Routes

typescript
// src/tests/integration/auth.test.tsimport request from 'supertest';import { app } from '../../app'; describe('Auth Routes', () => {  const userData = {    name: 'Test User',    email: 'test@example.com',    password: 'password123',  };   describe('POST /api/auth/register', () => {    it('should register new user', async () => {      const response = await request(app)        .post('/api/auth/register')        .send(userData);       expect(response.status).toBe(201);      expect(response.body).toHaveProperty('user');      expect(response.body).toHaveProperty('token');    });     it('should return error if email exists', async () => {      await request(app).post('/api/auth/register').send(userData);       const response = await request(app)        .post('/api/auth/register')        .send(userData);       expect(response.status).toBe(400);    });  });   describe('POST /api/auth/login', () => {    beforeEach(async () => {      await request(app).post('/api/auth/register').send(userData);    });     it('should login with valid credentials', async () => {      const response = await request(app)        .post('/api/auth/login')        .send({ email: userData.email, password: userData.password });       expect(response.status).toBe(200);      expect(response.body).toHaveProperty('token');    });     it('should reject wrong password', async () => {      const response = await request(app)        .post('/api/auth/login')        .send({ email: userData.email, password: 'wrong' });       expect(response.status).toBe(401);    });  });});

Test Helpers

typescript
// src/tests/helpers.tsimport request from 'supertest';import { app } from '../app'; export async function createTestUser() {  const response = await request(app)    .post('/api/auth/register')    .send({      name: 'Test User',      email: `test-${Date.now()}@example.com`,      password: 'password123',    });   return { user: response.body.user, token: response.body.token };} export function authRequest(token: string) {  return {    get: (url: string) => request(app).get(url).set('Authorization', `Bearer ${token}`),    post: (url: string) => request(app).post(url).set('Authorization', `Bearer ${token}`),  };}

Summary

  • ✅ Supertest for HTTP testing
  • ✅ Isolated test database
  • ✅ Test helpers
  • ✅ Auth and CRUD tests

Next lesson: Swagger Documentation! 🚀

Enjoyed the content? Your contribution helps keep everything online and free!

PIX:0737160d-e98f-4a65-8392-5dba70e7ff3e