denoland/deno · error · TypeError
beforeEach() requires a function
Error message
beforeEach() requires a function
What it means
t.beforeEach(fn) on the node:test context registers a hook run before each of this test's subtests. The implementation pushes fn onto an internal array and requires typeof fn === 'function'; otherwise it throws TypeError 'beforeEach() requires a function'.
Source
Thrown at ext/node/polyfills/testing.ts:1620
}
before(fn, _options) {
if (typeof fn !== "function") {
throw new TypeError("before() requires a function");
}
ArrayPrototypePush(this.#beforeHooks, fn);
}
after(fn, _options) {
if (typeof fn !== "function") {
throw new TypeError("after() requires a function");
}
ArrayPrototypePush(this.#afterHooks, fn);
}
beforeEach(fn, _options) {
if (typeof fn !== "function") {
throw new TypeError("beforeEach() requires a function");
}
ArrayPrototypePush(this.#beforeEachHooks, fn);
}
afterEach(fn, _options) {
if (typeof fn !== "function") {
throw new TypeError("afterEach() requires a function");
}
ArrayPrototypePush(this.#afterEachHooks, fn);
}
// Runs this context's `before()` hooks a single time, before its first
// subtest. Idempotent so it is safe to call from every subtest's step.
async _runBeforeHooksOnce() {
if (this.#beforeHooksRun) return;
this.#beforeHooksRun = true;
// deno-lint-ignore no-this-alias
const ctx = this;View on GitHub (pinned to 9ad36f7a2c)
Solutions
- Pass the function reference: t.beforeEach(seedRow)
- Reference the specific method when importing an object of helpers: t.beforeEach(hooks.seed)
- Check dynamically sourced hooks with typeof before registering
Example fix
// before t.beforeEach(resetDb()); // after t.beforeEach(resetDb);
Defensive patterns
Strategy: type-guard
Validate before calling
if (typeof seed !== 'function') {
throw new TypeError(`t.beforeEach: expected function, got ${typeof seed}`);
}
t.beforeEach(seed); Type guard
const isHookFn = (fn) => typeof fn === 'function';
if (isHookFn(seed)) {
t.beforeEach(seed);
} Prevention
- Reference helper objects' methods explicitly: t.beforeEach(hooks.seed)
- Do not pass a name string or describe block as the hook
- Validate dynamic hook sources with typeof before registering
When it happens
Trigger: t.beforeEach() with no argument; t.beforeEach(seedRow(...)) passing a query result; passing a describe-style name string first.
Common situations: Seed/reset helpers invoked instead of referenced; hook helpers imported as default objects and passed wholesale (t.beforeEach(hooks) where hooks.seed was meant).
Related errors
- before() requires a function
- after() requires a function
- afterEach() requires a function
- before() requires a function argument
- after() requires a function argument
AI-assisted analysis of denoland/deno@9ad36f7a2c (2026-08-20).
Data as JSON: /api/errors/9a3e5883f6eb6788.
Report an issue: GitHub.