Node.js ยท Chapter 37 of 43

Testing Node.js Apps

Automated tests verify your code behaves correctly and catch regressions before they reach production. Popular Node.js testing tools include Jest, Mocha, and the built-in `node:test` module.

Unit tests check individual functions in isolation, while integration tests verify how multiple parts (like routes and databases) work together.

Writing a unit test

A test typically calls a function with known input and asserts the output matches an expected value.

Testing an API endpoint

Libraries like `supertest` let you send fake HTTP requests to an Express app and assert on the response, without starting a real server.

Example 1 (javascript)
const { test } = require('node:test');
const assert = require('assert');
function add(a, b) { return a + b; }
test('adds numbers', () => {
  assert.strictEqual(add(2, 3), 5);
});
Output
โœ” adds numbers

The built-in node:test module runs the test and reports pass/fail.

Example 2 (javascript)
const request = require('supertest');
const app = require('./app');
request(app).get('/').expect(200).then(res => console.log(res.text));
Output
200 OK, response body logged

supertest simulates HTTP requests against the Express app in-memory for testing.

Key points

  • Automated tests catch regressions before production.
  • Unit tests isolate individual functions; integration tests check combined behaviour.
  • node:test is Node's built-in test runner (no install needed).
  • supertest is popular for testing Express routes.
๐Ÿ’ก Note: Aim to test critical business logic and edge cases, not just the happy path.

๐Ÿ“ Quick Quiz

1. What's the difference between a unit test and integration test?

2. Which module is Node's built-in test runner?

3. Which library is popular for testing Express HTTP endpoints?