Build a small JSON endpoint

Lesson 4 of 4 · 2 min read

Test the boundaries

Exercise the real HTTP handler with Node’s test runner and a temporary local port.

Demo lesson · not author-approved.

Add an integration test

Stop the manually running server. Create handler.test.js:

import test from 'node:test';
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { once } from 'node:events';
import { handler } from './handler.js';

test('greetings and invalid requests', async (t) => {
  const server = createServer(handler);
  server.listen(0, '127.0.0.1');
  await once(server, 'listening');
  t.after(() => new Promise((resolve, reject) => {
    server.close((error) => error ? reject(error) : resolve());
    server.closeAllConnections();
  }));
  const base = `http://127.0.0.1:${server.address().port}`;

  const greeting = await fetch(`${base}/hello?name=Ada`);
  assert.equal(greeting.status, 200);
  assert.deepEqual(await greeting.json(), { message: 'Hello, Ada!' });

  for (const path of ['/hello?name=', '/hello?name=A&name=B']) {
    const response = await fetch(base + path);
    assert.equal(response.status, 400);
    await response.arrayBuffer();
  }
  const missing = await fetch(`${base}/missing`);
  assert.equal(missing.status, 404);
  await missing.arrayBuffer();
  const post = await fetch(`${base}/hello`, { method: 'POST' });
  assert.equal(post.status, 405);
  assert.equal(post.headers.get('allow'), 'GET');
  await post.arrayBuffer();
});

Run the check

Run npm test. You should see one passing test. Port 0 asks the operating system for an available port, so this test does not rely on port 3000 being free.

The cleanup closes the server even if an assertion fails. That matters: a failing test should report the failure, not hang indefinitely.

Extend it yourself

Add checks for a missing name, a name containing only spaces, a 60-character name, and a 61-character name. These cases describe the exact edge of the contract.

You now have a complete local endpoint: a server, a validated handler, and a repeatable test. Keep this project local until you have a separate plan for production security and operations.