Start learning free

LESSON 133 OF 173 · BACKEND: TESTS AND RUNNING IT

Your First Test

Practice

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:

const test = require("node:test");
const assert = require("node:assert");

function addShipping(price) {
  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. Its 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: 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.


STEP 1 OF 4
    Ctrl + Enter to check