denoland/deno · error · TypeError
beforeEach() requires a function argument
Error message
beforeEach() requires a function argument
What it means
The module-level beforeEach(fn) from node:test registers a hook run before each test in the current suite (describe block) — or on the root hooks when called outside any suite. The first line of its implementation rejects non-functions with TypeError 'beforeEach() requires a function argument'.
Source
Thrown at ext/node/polyfills/testing.ts:2192
const tapSuite = getTapCurrentSuite();
if (tapSuite !== null) {
ArrayPrototypePush(tapSuite.afterAllHooks ??= [], fn);
return;
}
ArrayPrototypePush(rootAfterHooks, fn);
scheduleTapRun();
return;
}
if (currentSuite) {
ArrayPrototypePush(currentSuite.afterAllHooks, fn);
return;
}
ArrayPrototypePush(rootAfterHooks, fn);
}
function beforeEach(fn, _options) {
if (typeof fn !== "function") {
throw new TypeError("beforeEach() requires a function argument");
}
if (currentSuite) {
ArrayPrototypePush(currentSuite.beforeEachHooks, fn);
return;
}
ArrayPrototypePush(rootBeforeEachHooks, fn);
}
function afterEach(fn, _options) {
if (typeof fn !== "function") {
throw new TypeError("afterEach() requires a function argument");
}
if (currentSuite) {
ArrayPrototypePush(currentSuite.afterEachHooks, fn);
return;
}
ArrayPrototypePush(rootAfterEachHooks, fn);
}View on GitHub (pinned to 9ad36f7a2c)
Solutions
- Pass the function reference: beforeEach(resetState)
- Reference a specific method for helper objects: beforeEach(hooks.reset)
- Validate dynamically sourced hooks with typeof before registering
Example fix
// before beforeEach(seedRows()); // after beforeEach(seedRows);
Defensive patterns
Strategy: type-guard
Validate before calling
import { beforeEach } from 'node:test';
if (typeof seed !== 'function') {
throw new TypeError(`beforeEach: expected function, got ${typeof seed}`);
}
beforeEach(seed); Type guard
const isHookFn = (fn) => typeof fn === 'function';
if (isHookFn(seed)) {
beforeEach(seed);
} Prevention
- Pass the function reference, not its result
- For helper objects, pass a bound specific method: beforeEach(hooks.reset)
- Check typeof for any hook sourced from configuration or flags
When it happens
Trigger: beforeEach() with no argument; beforeEach(resetState()) passing the invocation result; beforeEach(describeBlock) passing a suite helper instead of a hook.
Common situations: Calling the helper instead of referencing it; copying hook registrations between suites and dropping the function; passing an imported object of helpers instead of a specific method.
Related errors
- before() requires a function argument
- after() requires a function argument
- afterEach() requires a function argument
- before() requires a function
- after() requires a function
AI-assisted analysis of denoland/deno@9ad36f7a2c (2026-08-20).
Data as JSON: /api/errors/76e4f36dae5a046d.
Report an issue: GitHub.