#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
•Question 22 of 28medium

How do you test APIs?

API testing strategies and tools.

What You'll Learn

  • Types of API tests
  • Testing tools
  • Implementation examples

Types of API Tests

  1. Unit tests - Individual functions
  2. Integration tests - API endpoints
  3. Contract tests - API agreements
  4. Load tests - Performance under load

Testing Tools

  • Jest/Mocha - Test frameworks
  • Supertest - HTTP assertions
  • Postman - Manual + automated
  • k6/Artillery - Load testing

Integration Test Example

code.jsJavaScript
const request = require('supertest');
const app = require('../app');

describe('Users API', () => {
  describe('GET /users', () => {
    it('should return all users', async () => {
      const res = await request(app)
        .get('/api/users')
        .expect('Content-Type', /json/)
        .expect(200);

      expect(res.body.data).toBeInstanceOf(Array);
      expect(res.body.meta).toHaveProperty('total');
    });
  });

  describe('POST /users', () => {
    it('should create a user', async () => {
      const res = await request(app)
        .post('/api/users')
        .send({ name: 'John', email: 'john@test.com' })
        .expect(201);

      expect(res.body.data).toHaveProperty('id');
      expect(res.body.data.name).toBe('John');
    });

    it('should return 422 for invalid data', async () => {
      const res = await request(app)
        .post('/api/users')
        .send({ name: '' })
        .expect(422);

      expect(res.body.error.code).toBe('VALIDATION_ERROR');
    });
  });
});

Testing with Authentication

code.jsJavaScript
let authToken;

beforeAll(async () => {
  const res = await request(app)
    .post('/api/login')
    .send({ email: 'test@test.com', password: 'password' });
  authToken = res.body.token;
});

it('should access protected route', async () => {
  await request(app)
    .get('/api/protected')
    .set('Authorization', `Bearer ${authToken}`)
    .expect(200);
});