Test runner with nested describe, beforeEach, and afterEach
Test frameworks such as Jest and Vitest let a suite share setup code: a beforeEach in an outer describe also runs for every test in the nested describe blocks, and an afterEach cleans up even when a test fails. In this problem you build the core of that scheduler.
Implement createTestRunner(). Each call returns a new, independent runner:
const runner = createTestRunner();
const { describe, it, beforeEach, afterEach } = runner;
describe(name, callback) // declares a suite
it(name, fn) // declares a test
beforeEach(fn) // declares a setup hook for the current suite
afterEach(fn) // declares a cleanup hook for the current suite
await runner.run() // => Array<{ name, status, error? }>
describe calls its callback immediately (synchronously) so that the tests and hooks inside it are registered. Suites can be nested to any depth.it, beforeEach and afterEach called outside any describe belong to the top-level (root) scope.run().beforeEach hooks of every enclosing scope, outermost scope first;afterEach hooks of every enclosing scope, innermost scope first.Within one scope, hooks run in the order they were declared. A hook applies to every test in its scope, including tests declared before the hook.
async functions). Wait for it before moving on. A rejected promise counts as a throw.beforeEach hook throws, skip the remaining beforeEach hooks and the test function. The test fails.afterEach hooks always run, all of them, even after a failure. If one throws, the remaining afterEach hooks still run and the test fails.run() returns a promise that always resolves (never rejects) with one result per test, in run order:
name: the suite names and the test name joined with ' > ', for example 'cart > discounts > applies coupon'. A root-level test’s name is just its own name.status: 'passed' or 'failed'.error: only on failed results. The thrown value’s message if it is an Error, otherwise String(value). Passed results have no error key.const runner = createTestRunner();
const { describe, it, beforeEach, afterEach } = runner;
const log = [];
beforeEach(() => log.push('open db'));
afterEach(() => log.push('close db'));
describe('cart', () => {
beforeEach(async () => log.push('seed cart'));
afterEach(() => log.push('clear cart'));
it('adds an item', () => log.push('test: add'));
describe('discounts', () => {
beforeEach(() => log.push('load coupons'));
it('rejects expired coupons', () => {
log.push('test: expired');
throw new Error('coupon accepted');
});
});
});
const results = await runner.run();
// results => [
// { name: 'cart > adds an item', status: 'passed' },
// { name: 'cart > discounts > rejects expired coupons', status: 'failed', error: 'coupon accepted' },
// ]
// log => [
// 'open db', 'seed cart', 'test: add', 'clear cart', 'close db',
// 'open db', 'seed cart', 'load coupons', 'test: expired', 'clear cart', 'close db',
// ]