Files
scriptc/tests/fixtures/node-test/cases/root-hooks.ts
T
Chris Tate d3dba4c07f Run module-level before and after hooks
node:test changes, matching Node 24.22:

- before and after hooks outside any suite run, with the root's context,
  whose name is "<root>". They did not run before.
- A module-level before hook runs at its before() call, as Node runs the
  hooks of its already-started root at once: its synchronous part runs
  before the code after the call, and the first top-level test waits for
  an async hook's promise. Every module-level before hook runs, and an
  async hook's rejection is not reported as an unhandled rejection.
- Module-level after hooks run after the last top-level test or suite.
- A throwing root before hook fails each top-level test with the first
  failure; the test's body and beforeEach hooks do not run, and its
  afterEach hooks do. Each top-level suite fails with the error, and the
  tests and suites in it are cancelled before they start: they report
  without a duration and fail with "test did not finish before its parent
  and was cancelled", listed in the failing section in completion order.
- A throwing root after hook reports the entry file as a failed result,
  after the top-level results, and lists it in the failing section at the
  hook's location. It is not counted, and the exit code is unchanged.
- Hooks record the "file:line:col" of their call for that location.

The root-hooks, root-before-throws and root-after-throws fixtures compare
the reporter output, the order of the hooks against the module code, and
the exit codes with Node, plain and with SCRIPTC_SAN=1.
2026-10-18 10:59:27 -05:00

45 lines
1.2 KiB
TypeScript

// Module-level before hooks run at their before() calls, with the root's
// context (named "<root>"), and the first top-level test waits for the
// async ones; module-level after hooks run after the last top-level test
// or suite, and module-level beforeEach hooks run before each test, with
// that test's context.
import { after, before, beforeEach, describe, it, test } from "node:test";
import * as assert from "node:assert";
const seen: string[] = [];
before((c) => {
seen.push(`before: ${c.name}`);
});
seen.push("after the before() call");
before(async () => {
seen.push("async before starts");
await new Promise<void>((resolve) => setTimeout(resolve, 5));
seen.push("async before ends");
});
beforeEach((c) => {
seen.push(`beforeEach: ${c.name}`);
});
after(() => {
// Throws, and so fails the run visibly, unless every hook ran in order.
assert.deepStrictEqual(seen, [
"before: <root>",
"after the before() call",
"async before starts",
"suite body",
"async before ends",
"beforeEach: x",
"beforeEach: t",
"report",
]);
});
describe("s", () => {
seen.push("suite body");
it("x", () => {});
});
test("t", () => {
seen.push("report");
});