Skip to content

Test Rules Without Rendering a Page

The Course
•
18 min study

The decision

Most of the Library's rules are plain functions: input in, output out. Testing them directly, without starting a server or rendering a page, gives fast tests whose failure names the rule that broke ("leaves out finished items") instead of only showing a wrong number somewhere on a screen.

Read, predict, run

lib/contract.js adds up the minutes left on unfinished items:

JavaScript
export function run(items) {
  return items
    .filter((item) => !item.done)
    .reduce((sum, item) => sum + item.minutes, 0);
}

tests/remaining.test.js tests it. Each test has a name that states one rule and an assertion that checks one exact result:

JavaScript
import { test, assert } from "@/lib/test.js";
import { run } from "@/lib/contract.js";

test("adds the minutes of unfinished items", () => {
  assert.equal(
    run([
      { minutes: 20, done: false },
      { minutes: 10, done: false },
    ]),
    30,
  );
});

test("leaves out finished items", () => {
  assert.equal(
    run([
      { minutes: 20, done: false },
      { minutes: 10, done: true },
    ]),
    20,
  );
});

test("an empty list is zero minutes", () => {
  assert.equal(run([]), 0);
});

lib/test.js is a small stand-in so the tests run in the browser; the page lists each result. It has the same shape as Node's built-in runner. In the downloadable project you write import { test } from "node:test" and import assert from "node:assert/strict", and npm test runs the file.

A test you've never seen fail proves little. So break the rule on purpose: in lib/contract.js, change !item.done to item.done. Predict which tests fail, and what each one reports, then run.

Test Rules Without Rendering a Page Next.js · 8 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; import Tests from "./Tests.jsx"; export default function Page() { return ( <main> <h1>Test Rules Without Rendering a Page</h1> <Tests /> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } import "@/tests/remaining.test.js"; import { runTests } from "@/lib/test.js"; export default async function Tests() { const results = await runTests(); return ( <section> <h2>Tests in tests/remaining.test.js</h2> <p> Tests: {results.filter((r) => r.pass).length}/{results.length} passed </p> <ul> {results.map((r) => ( <li key={r.name} className={r.pass ? "pass" : "fail"}> {r.pass ? "✓" : "✗"} {r.name} {r.message && `: ${r.message}`} </li> ))} </ul> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run(items) { return items .filter((item) => !item.done) .reduce((sum, item) => sum + item.minutes, 0); } export const examples = [ [ [ { minutes: 20, done: false }, { minutes: 10, done: true }, ], 20, ], [[], 0], ]; // A tiny stand-in for node:test and node:assert/strict, so tests can run in // the browser. On your computer, write instead: // import { test } from "node:test"; // import assert from "node:assert/strict"; const tests = []; export function test(name, fn) { tests.push({ name, fn }); } const show = (value) => JSON.stringify(value) ?? String(value); export const assert = { equal(actual, expected) { if (!Object.is(actual, expected)) throw new Error(`expected ${show(expected)}, got ${show(actual)}`); }, deepEqual(actual, expected) { if (show(actual) !== show(expected)) throw new Error(`expected ${show(expected)}, got ${show(actual)}`); }, }; export async function runTests() { const results = []; for (const { name, fn } of tests) { try { await fn(); results.push({ name, pass: true, message: "" }); } catch (error) { results.push({ name, pass: false, message: error.message }); } } return results; } import { test, assert } from "@/lib/test.js"; import { run } from "@/lib/contract.js"; test("adds the minutes of unfinished items", () => { assert.equal( run([ { minutes: 20, done: false }, { minutes: 10, done: false }, ]), 30, ); }); test("leaves out finished items", () => { assert.equal( run([ { minutes: 20, done: false }, { minutes: 10, done: true }, ]), 20, ); }); test("an empty list is zero minutes", () => { assert.equal(run([]), 0); });
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction
Text
Tests: 1/3 passed
✗ adds the minutes of unfinished items: expected 30, got 0
✗ leaves out finished items: expected 20, got 10
✓ an empty list is zero minutes

The broken filter keeps only finished items. The empty-list test still passes, because an empty list is zero either way: it guards against a crash, not against this mistake. That's fine, as long as some other test catches it. Undo the change.

The failure to avoid

A test that asserts only "the result is a number" passes for the broken filter too. Assert an exact value for a small, readable input, and include the edge case. Then make the deliberate mistake: if no test fails, you've found a rule nobody checks.

Exercise

Test first, then the rule

Archived items shouldn't count either. Do it in this order:

  1. Add a test named leaves out archived items to tests/remaining.test.js, using an unfinished, archived item with a large minutes.
  2. Run, and check that your new test fails against the current run.
  3. Change run in lib/contract.js until every test passes.

Add the case to examples in lib/contract.js as well:

  • Input [{"minutes": 100, "done": false, "archived": true}] must return 0.
Your working space Next.js · 8 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; import Tests from "./Tests.jsx"; export default function Page() { return ( <main> <h1>Test Rules Without Rendering a Page</h1> <Tests /> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } import "@/tests/remaining.test.js"; import { runTests } from "@/lib/test.js"; export default async function Tests() { const results = await runTests(); return ( <section> <h2>Tests in tests/remaining.test.js</h2> <p> Tests: {results.filter((r) => r.pass).length}/{results.length} passed </p> <ul> {results.map((r) => ( <li key={r.name} className={r.pass ? "pass" : "fail"}> {r.pass ? "✓" : "✗"} {r.name} {r.message && `: ${r.message}`} </li> ))} </ul> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run(items) { return items .filter((item) => !item.done) .reduce((sum, item) => sum + item.minutes, 0); } export const examples = [ [ [ { minutes: 20, done: false }, { minutes: 10, done: true }, ], 20, ], [[], 0], ]; // A tiny stand-in for node:test and node:assert/strict, so tests can run in // the browser. On your computer, write instead: // import { test } from "node:test"; // import assert from "node:assert/strict"; const tests = []; export function test(name, fn) { tests.push({ name, fn }); } const show = (value) => JSON.stringify(value) ?? String(value); export const assert = { equal(actual, expected) { if (!Object.is(actual, expected)) throw new Error(`expected ${show(expected)}, got ${show(actual)}`); }, deepEqual(actual, expected) { if (show(actual) !== show(expected)) throw new Error(`expected ${show(expected)}, got ${show(actual)}`); }, }; export async function runTests() { const results = []; for (const { name, fn } of tests) { try { await fn(); results.push({ name, pass: true, message: "" }); } catch (error) { results.push({ name, pass: false, message: error.message }); } } return results; } import { test, assert } from "@/lib/test.js"; import { run } from "@/lib/contract.js"; test("adds the minutes of unfinished items", () => { assert.equal( run([ { minutes: 20, done: false }, { minutes: 10, done: false }, ]), 30, ); }); test("leaves out finished items", () => { assert.equal( run([ { minutes: 20, done: false }, { minutes: 10, done: true }, ]), 20, ); }); test("an empty list is zero minutes", () => { assert.equal(run([]), 0); });
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

Seeing the test fail first proves it can detect the missing rule. A test written after the code, which has only ever passed, might be checking nothing.

Hint 2: a first step

Copy the leaves out finished items test and change its input: one item with minutes: 100, done: false and archived: true. What should the total be? Run: it fails with got 100. Now the rule.

Show one solution

In lib/contract.js:

JavaScript
export function run(items) {
  return items
    .filter((item) => !item.done && !item.archived)
    .reduce((sum, item) => sum + item.minutes, 0);
}

In tests/remaining.test.js:

JavaScript
test("leaves out archived items", () => {
  assert.equal(run([{ minutes: 100, done: false, archived: true }]), 0);
});

The large minutes makes the failure obvious: expected 0, got 100 can only mean the archived item was counted. The change goes in the filter, which decides what counts; the sum doesn't change. !item.archived also treats a missing archived as "not archived", so the older tests keep passing.

Explain it without the code

Pick one rule from the Library: a title is required, or a page past the end is clamped. Write a test name for it, the input, and the deliberate mistake that test should catch.

Going further

Read Node's test runner documentation for describe, beforeEach and running a single test. The next lesson tests the route handler around a rule like this one.

Was this article helpful?

Your response is saved on this device.