24.2. A test runner (describe, it, hooks)
Topics
This question is in
24. Build a small libraryTest 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
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
itonly registers a test. Nothing runs untilrun(), which runs every test in the order it was written (blocks are walked depth first) and returns the results in that order, withpassedandfailedcounts.- A test that throws fails; the next test still runs.
describecalls 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 anydescribebelong to an unnamed root block.- Before each test, the
beforeEachhooks of every block that contains it run, outermost block first, in the order they were added. After each test, theafterEachhooks run, innermost block first. A hook applies to every test of its block, even one added before the hook. afterEachhooks run even when the test or abeforeEachfailed. If abeforeEachthrows, the remainingbeforeEachhooks and the test body are skipped and the test fails with that error. A test keeps only the first error it meets.- A block's
beforeAllhooks run once, before its first test (nested blocks included), and itsafterAllhooks once, after its last. A block with no tests anywhere inside runs neither. - If a
beforeAllthrows, nothing else inside that block runs: each of its tests, nested ones included, is reported as failed with that error. The block'safterAllhooks still run, then the next block runs normally. - An
afterAllthat throws adds a failed result named after its block plus" > afterAll"(just"afterAll"for the root block). run()can be called again: it runs everything again and returns a fresh report. Two runners never share tests.- Every method that takes a function throws a
TypeErrorwith the message<method> expects a function(for exampleit expects a function) when it gets something else. - Adding a test, a block or a hook while
run()is running throws anErrorwith the messageCannot add tests while the runner is running. - If a
describebody throws, the error goes through to the caller, and tests added afterwards belong to the block that was current before thatdescribe.
Examples
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" } ] }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 afterEachconst r = createRunner();
r.describe("empty", () => { r.beforeAll(() => console.log("never")); });
r.run(); // { passed: 0, failed: 0, results: [] }, nothing loggedEnvironment
- Plain JavaScript in a browser page; the tests call the global
createRunnerfromrunner.js. - Everything is synchronous. Async tests, timeouts,
onlyandskipare out of scope (problem 24.3 adds async tests and timeouts). - Do not define globals named
testorexpect: the page's own test harness uses them.
Hints
- What does a block need to remember: its name, its parent, its hooks, and what else, so that the test order is kept?
- While
describeruns its function, how doesitknow which block to add to? What must happen to that "current block" when the function returns, or throws? - 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