API Development and Integration

Master RESTful API design, GraphQL, API security, documentation, and integration patterns.

advanced Backend Development 6 hours

Chapter 11: API Testing

Chapter 11 of 14

Chapter 11: API Testing

11.1 Testing APIs

Comprehensive API testing ensures reliability and catches bugs before production.

// Using Jest and Supertest
const request = require('supertest');
const app = require('./app');

describe('User API', () => {
    test('GET /api/users returns 200', async () => {
        const response = await request(app)
            .get('/api/users')
            .expect(200);
        
        expect(response.body).toBeInstanceOf(Array);
    });
    
    test('POST /api/users creates user', async () => {
        const userData = {
            name: 'Test User',
            email: 'test@example.com',
            password: 'password123'
        };
        
        const response = await request(app)
            .post('/api/users')
            .send(userData)
            .expect(201);
        
        expect(response.body).toHaveProperty('id');
        expect(response.body.email).toBe(userData.email);
    });
});

11.2 Integration Testing

// Test complete workflows
describe('User Workflow', () => {
    let userId;
    let authToken;
    
    test('creates and authenticates user', async () => {
        // Create user
        const createRes = await request(app)
            .post('/api/users')
            .send({ email: 'test@example.com', password: 'pass123' });
        
        userId = createRes.body.id;
        
        // Login
        const loginRes = await request(app)
            .post('/api/login')
            .send({ email: 'test@example.com', password: 'pass123' });
        
        authToken = loginRes.body.token;
        
        // Access protected route
        await request(app)
            .get(`/api/users/${userId}`)
            .set('Authorization', `Bearer ${authToken}`)
            .expect(200);
    });
});

11.3 API Testing Tools

  • Postman: GUI tool for API testing
  • Insomnia: REST client with testing features
  • Newman: CLI for running Postman collections
  • Supertest: Node.js library for HTTP assertions