Chapter 13: Testing Node.js Applications
Chapter 13 of 15
Chapter 13: Testing Node.js Applications
13.1 Unit and Integration Testing
Testing ensures code quality and prevents regressions. Use Jest, Mocha, or other testing frameworks.
// Jest example
const { sum, multiply } = require('./math');
describe('Math functions', () => {
test('adds two numbers', () => {
expect(sum(2, 3)).toBe(5);
});
test('multiplies two numbers', () => {
expect(multiply(2, 3)).toBe(6);
});
});
13.2 Testing Async Code
// Testing promises
test('fetches user data', async () => {
const user = await fetchUser(1);
expect(user).toHaveProperty('id');
expect(user.id).toBe(1);
});
// Testing callbacks
test('handles callback', (done) => {
asyncFunction((err, result) => {
expect(err).toBeNull();
expect(result).toBeDefined();
done();
});
});
13.3 Mocking
// Mock modules
jest.mock('./database');
const db = require('./database');
test('creates user', async () => {
db.createUser.mockResolvedValue({ id: 1, name: 'John' });
const user = await createUser({ name: 'John' });
expect(db.createUser).toHaveBeenCalledWith({ name: 'John' });
expect(user.id).toBe(1);
});
13.4 Integration Testing
// Test API endpoints
const request = require('supertest');
const app = require('./app');
describe('User API', () => {
test('GET /users', async () => {
const response = await request(app)
.get('/users')
.expect(200);
expect(response.body).toBeInstanceOf(Array);
});
test('POST /users', async () => {
const response = await request(app)
.post('/users')
.send({ name: 'John', email: 'john@example.com' })
.expect(201);
expect(response.body).toHaveProperty('id');
});
});