Skip to curriculum
Jump to the editor

24.2. A test runner (describe, it, hooks)

Medium
Topics

This question is in

24. Build a small library
35–50 min

Test frameworks look large, but their core is small: a tree of named blocks, a list of tests in each, and hooks that run around them. describe builds the tree, it adds a leaf, and run walks the tree, calling each test inside a try so one failure never stops the others. Writing that core is the best way to understand why hooks run in the order they do.

Write createRunner() in runner.js. It returns a synchronous test runner: tests are plain functions that pass by returning and fail by throwing.

Signature

JAVASCRIPT
function createRunner() // returns the object below

const r = createRunner();
r.describe(name, fn);   // runs fn now; what fn adds belongs to this block
r.it(name, fn);         // adds a test to the current block
r.beforeAll(fn);  r.afterAll(fn);    // once around the block's tests
r.beforeEach(fn); r.afterEach(fn);   // around every test of the block
r.run();                // returns { passed, failed, results }

Each result is { name, status: "pass" } or { name, status: "fail", error }, where error is the thrown value's message when it is an Error, and String(value) otherwise.

Requirements

  1. it only registers a test. Nothing runs until run(), which runs every test in the order it was written (blocks are walked depth first) and returns the results in that order, with passed and failed counts.
  2. A test that throws fails; the next test still runs.
  3. describe calls its function at once. Tests and hooks added during that call belong to the block. A test's name is the names of its blocks and its own, joined with " > ". Tests and hooks added outside any describe belong to an unnamed root block.
  4. Before each test, the beforeEach hooks of every block that contains it run, outermost block first, in the order they were added. After each test, the afterEach hooks run, innermost block first. A hook applies to every test of its block, even one added before the hook.
  5. afterEach hooks run even when the test or a beforeEach failed. If a beforeEach throws, the remaining beforeEach hooks and the test body are skipped and the test fails with that error. A test keeps only the first error it meets.
  6. A block's beforeAll hooks run once, before its first test (nested blocks included), and its afterAll hooks once, after its last. A block with no tests anywhere inside runs neither.
  7. If a beforeAll throws, nothing else inside that block runs: each of its tests, nested ones included, is reported as failed with that error. The block's afterAll hooks still run, then the next block runs normally.
  8. An afterAll that throws adds a failed result named after its block plus " > afterAll" (just "afterAll" for the root block).
  9. run() can be called again: it runs everything again and returns a fresh report. Two runners never share tests.
  10. Every method that takes a function throws a TypeError with the message <method> expects a function (for example it expects a function) when it gets something else.
  11. Adding a test, a block or a hook while run() is running throws an Error with the message Cannot add tests while the runner is running.
  12. If a describe body throws, the error goes through to the caller, and tests added afterwards belong to the block that was current before that describe.

Examples

JAVASCRIPT
const r = createRunner();
r.describe("cart", () => {
  r.beforeEach(() => console.log("new cart"));
  r.it("starts empty", () => {});
  r.it("adds an item", () => { throw new Error("Expected 1, got 0"); });
});
r.run();
// logs "new cart" twice
// { passed: 1, failed: 1, results: [
//   { name: "cart > starts empty", status: "pass" },
//   { name: "cart > adds an item", status: "fail", error: "Expected 1, got 0" } ] }
JAVASCRIPT
const r = createRunner();
r.describe("outer", () => {
  r.beforeAll(() => console.log("beforeAll"));
  r.beforeEach(() => console.log("outer beforeEach"));
  r.afterEach(() => console.log("outer afterEach"));
  r.describe("inner", () => {
    r.beforeEach(() => console.log("inner beforeEach"));
    r.afterEach(() => console.log("inner afterEach"));
    r.it("t", () => console.log("test"));
  });
});
r.run();
// beforeAll, outer beforeEach, inner beforeEach, test, inner afterEach, outer afterEach
JAVASCRIPT
const r = createRunner();
r.describe("empty", () => { r.beforeAll(() => console.log("never")); });
r.run(); // { passed: 0, failed: 0, results: [] }, nothing logged

Environment

  • Plain JavaScript in a browser page; the tests call the global createRunner from runner.js.
  • Everything is synchronous. Async tests, timeouts, only and skip are out of scope (problem 24.3 adds async tests and timeouts).
  • Do not define globals named test or expect: the page's own test harness uses them.

Hints

  1. What does a block need to remember: its name, its parent, its hooks, and what else, so that the test order is kept?
  2. While describe runs its function, how does it know which block to add to? What must happen to that "current block" when the function returns, or throws?
  3. For one test, which blocks' hooks apply? How do you get that list when you walk down the tree?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…