Linter · Rules
jest/no-hooks
Disallow beforeAll, beforeEach, afterEach and afterAll
A hook usually sets a variable that every test in the block shares. To understand one test, you have to find the hooks above it, and a test that changes the shared value can break the next one. A test that calls a setup function itself shows everything it depends on.
Configure
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"jest/no-hooks" = "error" # or "warn"
Every option, set to its default:
bunfig.toml
[lint.rules]
"jest/no-hooks" = ["error", {
allow = [], # list of strings
}]
Examples
Reported:
import { beforeEach, expect, test } from "@jest/globals";
let cart;
beforeEach(() => {
cart = createCart();
});
test("starts empty", () => {
expect(cart.items).toEqual([]);
});
Not reported:
import { expect, test } from "@jest/globals";
test("starts empty", () => {
const cart = createCart();
expect(cart.items).toEqual([]);
});
Options
| Option | Default | What it does |
|---|---|---|
allow | [] | Names of hooks to allow. |
With { "allow": ["afterEach"] }, only beforeAll is reported here:
import { afterEach, beforeAll, jest } from "@jest/globals";
afterEach(() => {
jest.restoreAllMocks();
});
beforeAll(() => {
server.listen();
});
When not to use it
Hooks are the usual way to start something slow once per file, such as a server or a database, and to stop it afterwards. If your tests do that, allow those hooks or leave the rule off.