Courses / Node.js: From First Script to Production / Chapter 21
Module 9 · Tests, types and operations · Chapter 21 of 27
Testing Node Code with node:test
Builds on Working with Databases: A REST API on PostgreSQL. Next up: TypeScript for Node: Type Stripping, tsconfig and Typed Handlers.
Part 1 · What to test and a first test
Three kinds of test
A food stall at a college fest gives 10 per cent off with a coupon, and rounds the discount in the wrong direction. Nobody notices for a week, and by then it has cost a few paise on every order.
A test is a small program that runs your code with known input and checks the result against what you expect. When the code changes later, you run the tests again and learn quickly whether something broke. Tests for a Node service come in three kinds, named by how much of the system they run at once.
| Kind | What runs | Typical speed | What it catches |
|---|---|---|---|
| Unit test | One function or class, with its collaborators replaced | Milliseconds | Wrong rules, rounding, edge cases |
| Integration test | Several parts together, such as the API and a database | Tens to hundreds of milliseconds | Wrong SQL, wrong status codes, wiring mistakes |