Advanced Web Applications Development

Labs · Lab

Lab D — tests that fail when the code is wrong

Write two tests for fare search, prove they catch a real break, then push and watch them run on GitHub Actions.

In this lab

  • Writing a test that asserts the rule, not the number
  • Watching a test pass against broken code, and fixing the test
  • Running the whole suite on GitHub Actions
Time
25 min
Start from
checkpoint/lab-c-done
Finish at
checkpoint/lab-d-done

Two tests already run in this project. You are adding two more, for the search you built in Lab A.

The lab is short, and the point is not “write tests”. It is that a test which passes when the code is broken is worse than no test, because it tells you the thing is fine. You will write one of those on purpose, watch it pass a broken search, and then fix the test.

Catch up

git checkout checkpoint/lab-c-done
npm run reset
node prisma/create-user.js

Steps

1. Make a new test file. tests/fares.test.js, with the same withServer helper the existing tests use — start the real app on a port the operating system picks, talk to it with fetch, close it afterwards. Copy it from tests/health.test.js.

2. Write the first test: a search returns a fare. Westfield is stop 1 and Brikama is stop 8 in the seed, every time.

Resist asserting amountDalasi === 45. Lab B asked everyone to add their own fare to a route, so the amount is allowed to change — a test that breaks when a teammate adds real data is a test people start ignoring. Assert the rule instead:

test('a fare search returns the fare that is in effect today', async () => {
  await withServer(async (base) => {
    const response = await fetch(`${base}/api/fares?from=1&to=8`);
    const fare = await response.json();

    assert.equal(response.status, 200);
    assert.equal(fare.from, 'Westfield');

    const effective = new Date(fare.effectiveFrom);

    assert.ok(effective <= new Date(), 'a fare starting in the future must not be returned');
  });
});

3. Write the second test: a missing route is a 404. Brikama to Westfield was never seeded, because a route runs one way:

test('a route nobody has entered returns 404, not an empty answer', async () => {
  await withServer(async (base) => {
    const response = await fetch(`${base}/api/fares?from=8&to=1`);
    const body = await response.json();

    assert.equal(response.status, 404);
    assert.match(body.error, /No route/);
  });
});

4. Run them.

npm test

Four tests, four passing.

5. Now break the search on purpose. In api/routes/fares.js, inside the fares block of the GET handler, comment out the date filter and flip the order:

fares: {
  // where: { effectiveFrom: { lte: new Date() } },
  orderBy: { effectiveFrom: 'asc' },
  take: 1,
},

That is a genuinely broken search. It now returns the oldest fare — the 2025 one, before the April rise. Run npm test again.

All four tests still pass.

Sit with that for a second. The code is wrong, the app is lying to passengers about the price, and the suite is green.

6. Work out why. The assertion only asked whether the fare had already started. The 2025 fare has also already started. The test was checking half a rule.

7. Fix the test, not the code yet. The seed gives this route a 2025 fare and an April 2026 fare, so a correct answer can never be older than April. Add this second assertion below the one from step 2:

assert.ok(
  effective >= new Date('2026-04-01'),
  'returned a stale fare — check the orderBy and the take'
);

Run npm test. Now it fails, and the message says what to look at.

8. Put the code back and watch it go green again.

9. Push, and watch a machine do it.

git add -A
git commit -m "Lab D: tests for fare search"
git push

Open your fork on GitHub and click the Actions tab.

Checkpoint

With the code correct:

✔ a fare search returns the fare that is in effect today
✔ a route nobody has entered returns 404, not an empty answer
✔ the server is up and can reach the database
✔ the stops list is seeded
ℹ pass 4
ℹ fail 0

With the search broken, exactly one test fails, and it names the fix:

✖ a fare search returns the fare that is in effect today
  AssertionError: returned a stale fare — check the orderBy and the take
ℹ pass 3
ℹ fail 1

On GitHub, the run goes green. It started a PostgreSQL 18 container, pushed the schema into it, seeded it and ran all four tests — on a machine that has never seen your laptop. That is the point: the tests do not depend on anything you set up by hand.

If it breaks

Tests pass locally, fail on GitHub — read the log. Usually the workflow skipped npm run seed, so the stops are missing and every search is a 404.

“relation does not exist” on GitHub — npx prisma db push did not run before the tests.

Every test fails locally with a connection error — your database is not running, or .env is missing. npm run setup.

The 404 test fails with a 200 — someone seeded Brikama → Westfield. Pick another pair that has never been entered.

The finished file

tests/fares.test.js as it stands on checkpoint/lab-d-done — with the step 7 assertion in place, so this version fails against the broken search rather than passing it. It also asserts a couple of things the steps left out; those are habits, not requirements.

import 'dotenv/config';
import test from 'node:test';
import assert from 'node:assert/strict';
import { app } from '../api/app.js';

async function withServer(run) {
  const server = app.listen(0);
  await new Promise((resolve) => server.once('listening', resolve));

  try {
    await run(`http://127.0.0.1:${server.address().port}`);
  } finally {
    await new Promise((resolve) => server.close(resolve));
  }
}

// Westfield is stop 1 and Brikama is stop 8 in the seed, every time.
test('a fare search returns the fare that is in effect today', async () => {
  await withServer(async (base) => {
    const response = await fetch(`${base}/api/fares?from=1&to=8`);
    const fare = await response.json();

    assert.equal(response.status, 200);
    assert.equal(fare.from, 'Westfield');
    assert.equal(fare.to, 'Brikama');

    // Not "equals 45". Lab B invites everyone to add their own fare to this
    // route, so the amount is allowed to change. What must never change is
    // the rule, and the rule has two halves.
    assert.ok(Number.isInteger(fare.amountDalasi), 'the amount should be a whole number');

    const effective = new Date(fare.effectiveFrom);

    // Half one: it has already started.
    assert.ok(effective <= new Date(), 'a fare starting in the future must not be returned');

    // Half two: it is the *latest* one that has started. The seed gives this
    // route a 2025 fare and an April 2026 fare, so anything older than April
    // means the search found a fare, just not the right one.
    assert.ok(
      effective >= new Date('2026-04-01'),
      'returned a stale fare — check the orderBy and the take'
    );
  });
});

test('a route nobody has entered returns 404, not an empty answer', async () => {
  await withServer(async (base) => {
    // A route runs one way, and Brikama to Westfield was never seeded.
    const response = await fetch(`${base}/api/fares?from=8&to=1`);
    const body = await response.json();

    assert.equal(response.status, 404);
    assert.match(body.error, /No route/);
  });
});

Stretch

  1. Test the guard from Lab C. Assert that POSTing a fare without a session returns 401, and that it returns 201 with one. You will need to pass the cookie between the two requests yourself.
  2. Make the suite independent of the seed. Have the test create its own stop, route and two fares, assert against those, then delete them. Harder than it sounds, and it is why test databases exist.

For trainers

This lab has the most transferable idea in the module, and it is worth protecting the time for step 5. If you cut anything here, cut the stretch tasks, not the broken-search demonstration.

  1. Where would your students get stuck first?
  2. What would you cut if you had fifteen minutes instead of twenty-five?
  3. What would you add that is missing here?
Saved in this browser only.