Backend

Testing it with node:test

Node ships a test runner. Twelve tests cover the router and the middleware, and none of them opens a port.

An editor showing a test file that imports test from node:test and asserts on a response.

Lene reviewed chapter 4 and asked where the tests were. Fair question. This chapter adds them, with the runner Node has shipped since version 18, and none of them starts the server.

Because handlers take a Request and return a Response, a test builds a request, calls match, and reads the response. No port, no client, no waiting.

Run the tests

$ pnpm test
$ npm test
{
  "type": "module",
  "scripts": {
    "test": "node --test test/"
  }
}

A test for the router

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { match, route } from '../src/router.ts';

const get = (path: string) => new Request(`http://localhost${path}`);

route('GET', '/posts/:slug', (req, { slug }) => new Response(`You asked for: ${slug}`));

test('hands the slug to the handler', async () => {
  const res = await match(get('/posts/hello'));
  assert.equal(await res.text(), 'You asked for: hello');
});

test('answers 404 for an unknown path', async () => {
  const res = await match(get('/nope'));
  assert.equal(res.status, 404);
});

What we did not test

node:http itself, and the four lines that turn its request into a Request. Node tests the first; the second is covered by one curl in chapter 6. Twelve tests run in 41 ms on my laptop.

audio-thumbnail
The sound my terminal plays when the suite passes
0:00
/2

Comments

Buy Logbuch