Skip to main content
← ⚑ JavaScript & the browserΒ·Module C8 Β· Lesson 3
TaskBuild tests = [], test(name, fn), runAll(). Register 3 tests: 'adds' asserting 1+1===2; 'subtracts' asserting 5-3===2; 'fails on purpose' asserting 1===2. Call runAll(). Output should show 2 pass, 1 fail.

Roll-your-own test runner

150 XP10 min
Theory

test() collects, runAll() reports

A real test runner is two functions and an array:

const tests = [];
function test(name, fn) {
  tests.push({ name, fn });
}

function runAll() {
  let passed = 0, failed = 0;
  for (const { name, fn } of tests) {
    try {
      fn();
      console.log("PASS " + name);
      passed++;
    } catch (err) {
      console.log("FAIL " + name + " β€” " + err.message);
      failed++;
    }
  }
  console.log(passed + " passed, " + failed + " failed");
}

That's it. test("foo works", () => { assertEqual(...) }) registers a test. runAll() executes them all, recovers from each failure, logs the result.

The same shape Vitest / Jest expose

The famous frameworks add: parallel execution, watch mode, snapshot diffing, coverage. But the core API β€” test(name, fn) and "run all and report" β€” is what you just built.

πŸ”’

Sign up to start coding

Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial β€” card required, cancel anytime.

Sign up β€” free trial β†’

First 10 lessons in each track are free. No card needed for those.

← PreviousNext lesson β†’

Get one Python or web tip a day β€” by email

Short, hand-written, no spam. Unsubscribe in one click.