Node.js Testing — Jest, Supertest & Test-Driven Development

Write tests for Node.js APIs with Jest and Supertest: unit tests, integration tests, mocking, and TDD workflow.

Node.js Intermediate 📖 10 min

Setup

npm install --save-dev jest supertest

Unit Testing

// math.js
function add(a, b) { return a + b; }
function divide(a, b) {
  if (b === 0) throw new Error('Division by zero');
  return a / b;
}

// math.test.js
describe('Math functions', () => {
  test('add adds two numbers', () => {
    expect(add(2, 3)).toBe(5);
  });
  
  test('divide divides two numbers', () => {
    expect(divide(10, 2)).toBe(5);
  });
  
  test('divide throws on zero', () => {
    expect(() => divide(10, 0)).toThrow('Division by zero');
  });
});

API Integration Tests

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

describe('Users API', () => {
  test('GET /api/users returns list', async () => {
    const res = await request(app)
      .get('/api/users')
      .expect(200);
    
    expect(Array.isArray(res.body.data)).toBe(true);
  });
  
  test('POST /api/users creates user', async () => {
    const res = await request(app)
      .post('/api/users')
      .send({ name: 'Alice', email: 'alice@test.com' })
      .expect(201);
    
    expect(res.body.name).toBe('Alice');
  });
});

Mocking

// Mock external service
jest.mock('../services/emailService', () => ({
  sendEmail: jest.fn().mockResolvedValue({ sent: true })
}));

const emailService = require('../services/emailService');

test('sends welcome email', async () => {
  await registerUser({ name: 'Alice', email: 'alice@test.com' });
  expect(emailService.sendEmail).toHaveBeenCalledWith(
    expect.objectContaining({ to: 'alice@test.com' })
  );
});

Ready to Level Up Your Coding Skills?

Join Coderz Club and learn to code with challenges, battles, and an AI mentor.

Join Coderz Club Free →