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.
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);
});โ adds numbersThe built-in node:test module runs the test and reports pass/fail.
const request = require('supertest');
const app = require('./app');
request(app).get('/').expect(200).then(res => console.log(res.text));200 OK, response body loggedsupertest 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.
