bun:test/require-hook
Require setup and teardown code to be inside a hook
Code at the top level of a test file, or directly in the body of a describe, runs once while bun test collects the tests. It runs even if every test in that block is skipped, and the state it builds is shared by all tests, so one test can break the next. Put it in beforeAll, beforeEach, afterEach or afterAll.
Two things are reported in those places:
- a statement that's only a function call, such as
setup(); - a
letorvarthat starts with a value other thannullorundefined
const declarations are allowed. So are calls to describe, test, it and the hooks, setDefaultTimeout(), expectTypeOf(), and calls on mock, expect, jest and vi, such as mock.module() and expect.extend().
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"bun:test/require-hook" = "error" # or "warn"Every option, set to its default:
bunfig.toml
[lint.rules]
"bun:test/require-hook" = ["error", {
allowedFunctionCalls = [], # list of strings
}]Examples#
example.ts3 problems
import { describe, expect, test } from "bun:test";
let db = connect();Require setup and teardown code to be within a hook.
db.seed(["ada", "grace"])Require setup and teardown code to be within a hook.;
describe("users", () => {
clearCache()Require setup and teardown code to be within a hook.;
test("finds a user", () => {
expect(db.find("ada")).toBeDefined();
});
});example.tsNo problems
import { beforeAll, beforeEach, describe, expect, mock, setDefaultTimeout, test } from "bun:test";
setDefaultTimeout(10_000);
mock.module("./mailer", () => ({ send: mock() }));
const names = ["ada", "grace"];
let db;
beforeAll(() => {
db = connect();
db.seed(names);
});
describe("users", () => {
beforeEach(() => {
clearCache();
});
test("finds a user", () => {
expect(db.find("ada")).toBeDefined();
});
});Options#
| Option | Default | What it does |
|---|---|---|
allowedFunctionCalls | [] | Names of functions that you can call outside a hook. Write a method with its object, like "db.seed". |
example.tswith
{ "allowedFunctionCalls": ["installMatchers", "db.seed"] }No problemsimport { expect, test } from "bun:test";
installMatchers();
db.seed(["ada"]);
test("finds a user", () => {
expect(db.find("ada")).toBeUser();
});