vitest/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]
"vitest/no-hooks" = "error" # or "warn"Every option, set to its default:
bunfig.toml
[lint.rules]
"vitest/no-hooks" = ["error", {
allow = [], # list of strings
}]Examples#
example.ts1 problem
import { beforeEach, expect, test } from "vitest";
let cart;
beforeEachDo not use setup or teardown hooks.(() => {
cart = createCart();
});
test("starts empty", () => {
expect(cart.items).toEqual([]);
});example.tsNo problems
import { expect, test } from "vitest";
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:
example.tswith
{ "allow": ["afterEach"] }1 problemimport { afterEach, beforeAll, vi } from "vitest";
afterEach(() => {
vi.restoreAllMocks();
});
beforeAllDo not use setup or teardown hooks.(() => {
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.