Testing APIs
Automated tests let you change code without fear: run one command and know in seconds whether everything still works. Node has a complete test runner built in (node:test) and an assertion library (node:assert), so you don't need to install anything.
Your first tests
Save tests in files ending in .test.js and run all of them with:
node --test # finds **/*.test.js and similar files
node --test --watch # re-runs when files changeAssertions
| Assertion | Passes when |
|---|---|
assert.equal(actual, expected) |
actual === expected (with assert/strict) |
assert.deepEqual(a, b) |
Objects/arrays have the same contents |
assert.ok(value) |
value is truthy |
assert.match(string, /regex/) |
The string matches |
assert.throws(fn, ErrorType) |
fn() throws that kind of error |
await assert.rejects(promise) |
The promise rejects |
When a test fails, the report tells you exactly what differed:
Grouping and setup
describe groups related tests, and hooks prepare and clean up shared state:
Testing an Express API
The best API tests send real HTTP requests to your app. Export the app without calling listen, then in the tests start it on port 0 (which means "any free port") and call it with fetch:
Many projects use supertest for the same job (request(app).get('/notes').expect(200)), and Vitest or Jest as the test runner. The ideas are identical.
Mocks: replacing dependencies
Code that sends emails, charges cards or calls other APIs shouldn't do that in tests. Pass dependencies in, and replace them with mocks in the test:
What to test
- Unit tests check one function on its own: fast, many of them.
- Integration tests check pieces together: routes + database, like the API test above.
- End-to-end tests drive the whole system like a user (Playwright, Cypress): slow, few of them.
Test the behaviour users depend on: successful requests, validation errors, authentication failures, not-found cases. Run the tests on every push with continuous integration (GitHub Actions: run: node --test).
Practice
- Add tests for
GET /notesafter creating two notes: it should return both, in order. - Write a failing test first for a
DELETE /notes/:idroute, then implement the route until it passes (that's test-driven development). - Use
mock.fn()to test that acheckout()function callspayments.charge(amount)with the cart total.
1.Why start the app with app.listen(0) in tests?
2.What does assert.deepEqual([1, 2], [1, 2]) check?
3.What's the main benefit of passing a mailer into registerUser instead of importing it?