Skip to curriculum
Jump to the editor

24.3. An async test runner with timeouts and a report

Hard
Topics

This question is in

24. Build a small library
45–70 min

Most real tests are asynchronous: they wait for a fetch, a timer or a database. A runner must wait for each test's promise, run the tests one at a time so they do not trample each other's state, and give up on a test that never finishes, so one forgotten resolve cannot freeze the whole suite. At the end it prints a short report.

Write createRunner(options) and formatReport(report) in async-runner.js.

Signature

JAVASCRIPT
function createRunner(options) // options: { timeout } in ms, default 2000

const r = createRunner({ timeout: 100 });
r.it(name, fn, { timeout });  // the third argument is optional
r.beforeEach(fn);
r.afterEach(fn);
r.run();                      // returns a promise of the report

function formatReport(report) // returns a string

The report:

JAVASCRIPT
{
  total, passed, failed,
  duration,      // ms from the start of run() to its end
  results: [
    { name, status: "pass", duration },
    { name, status: "fail", duration, error },  // error: the message, as text
  ],
}

error is the thrown or rejected value's message when it is an Error, and String(value) otherwise. Durations are measured with Date.now().

Requirements

  1. A test (or hook) passes when fn returns, or when the promise or thenable it returns resolves. It fails when fn throws synchronously or its promise rejects. The run goes on after a failure.
  2. Tests run one at a time, in the order they were added: a test starts only after the previous one, with its hooks, has finished.
  3. A test that has not settled after its timeout fails with the error Timed out after <ms> ms, and the run moves on. A test that settles before the timeout passes or fails normally.
  4. The timeout is it's timeout option when given (not undefined), else the runner's timeout, else 2000 ms.
  5. When a step settles in time, its timeout timer is cleared: no timer is left waiting after run() finishes.
  6. A test that settles after its timeout does not change its result, and a late rejection never becomes an unhandled rejection.
  7. Before each test, the beforeEach hooks run in order, each awaited; after it, the afterEach hooks run in order, each awaited, even when the test failed or timed out. A failing beforeEach skips the remaining beforeEach hooks and the test body. A test keeps only its first error.
  8. Each hook gets the same timeout as its test. A hook that times out fails the test with beforeEach timed out after <ms> ms or afterEach timed out after <ms> ms.
  9. A test's duration runs from the start of its first beforeEach to the end of its last afterEach.
  10. Calling run() while a run is in progress returns a promise that rejects with an Error with the message The runner is already running. Once the run has finished, run() works again.
  11. A timeout (in createRunner or in it) that is not a positive, finite number throws a RangeError with the message timeout must be a positive number. Only a missing or undefined timeout means "use the default"; null is a value given, and is refused like 0.
  12. it, beforeEach and afterEach throw a TypeError with the message <method> expects a function (for example it expects a function) when fn is not a function.
  13. formatReport writes PASS <name> (<duration> ms) or FAIL <name> (<duration> ms) for each result, puts the error on the next line after two spaces, and ends with <total> tests: <passed> passed, <failed> failed (<duration> ms), with test singular when the total is 1. Lines are joined with "\n", with no newline at the end.

Examples

JAVASCRIPT
const r = createRunner({ timeout: 50 });
r.it("loads user", () => new Promise((resolve) => setTimeout(resolve, 12)));
r.it("saves user", () => new Promise(() => {}));   // never settles

const report = await r.run();
// { total: 2, passed: 1, failed: 1, duration: 62, results: [
//   { name: "loads user", status: "pass", duration: 12 },
//   { name: "saves user", status: "fail", duration: 50, error: "Timed out after 50 ms" } ] }

console.log(formatReport(report));
// PASS loads user (12 ms)
// FAIL saves user (50 ms)
//   Timed out after 50 ms
// 2 tests: 1 passed, 1 failed (62 ms)
JAVASCRIPT
const r = createRunner();
r.it("slow upload", () => upload(), { timeout: 5000 });  // its own timeout
r.it("sync throw", () => { throw new Error("bad"); });   // fails, the run goes on
JAVASCRIPT
createRunner({ timeout: 0 });       // throws RangeError: timeout must be a positive number
createRunner({ timeout: null });    // throws the same RangeError; only a missing timeout means 2000
const r = createRunner();
r.run(); r.run();                   // the second rejects: The runner is already running

Environment

  • Plain JavaScript in a browser page; the tests call the globals createRunner and formatReport from async-runner.js.
  • The tests replace setTimeout, clearTimeout and Date.now with a virtual clock, so use those for timeouts and durations.
  • describe blocks, beforeAll, afterAll, done callbacks and running tests in parallel are out of scope (problem 24.2 covers describe and nested hooks).
  • Do not define globals named test or expect: the page's own test harness uses them.

Hints

  1. How do you turn "whatever fn does", a value, a throw, a promise or a thenable, into one promise you can await?
  2. A promise can be settled only once. How does that help when a timer and the test race to settle the same promise?
  3. Why does tests.forEach(async (t) => …) break requirement 2, and what kind of loop keeps it?

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…