Until now you checked your shop by hand: send a request, read the answer, decide if it's right. A test is code that does this for you, every time you run it, so you notice at once when a change breaks something. Node comes with the node:test module for writing tests.
A test is a call to test with two things: a name that says what the test checks, and a function that does the checking. assert.strictEqual(a, b), from Node's assert module, checks that two values are equal: if they differ, the test fails and shows both. Here is a test for a small function, not for the shop:
import test from "node:test";
import assert from "node:assert";
function addShipping(price: number): number {
return price + 5;
}
test("add shipping", () => {
assert.strictEqual(addShipping(10), 15);
});
A test doesn't start a server. The supertest package does that for it: request(app) makes a test client. It is loaded with require, and comes without TypeScript types, so TypeScript treats what it gives back as any. The client's get method sends a request straight to the app and gives back the response, with the status in response.status. The response takes a moment to arrive, so you write await before the call, in an async function. The shop is loaded for you as app, and it answers GET /products with 200 and its four products. The check runs your test on the shop, then on a broken copy that lost its GET /products route, and must print:
Your tests on the shop:
products answer 200 ... ok
1 test: OK
Your tests on a copy that lost its GET /products route:
products answer 200 ... FAIL
AssertionError: 404 != 200
1 test: 1 failed, so they caught this bug
Your task: below the three lines at the top, write one test named "products answer 200", with an async function that makes a test client for app, sends GET /products and checks that response.status is 200.
Assignment
Follow the Coding Tutorial to write your first test: a test, a test client, a request and one check.
Hint
In assert.strictEqual, put what you got first and what you expect second. A test with no check passes on any shop, even a broken one, so don't forget the last line.
Free plan: 30 tutor messages. PRO is unlimited.
