jest/prefer-hooks-in-order

Require hooks to be written in the order they run

Jest runs hooks in a fixed order: beforeAll, beforeEach, afterEach, afterAll. If a file lists them in another order, you read the teardown before the setup it undoes.

Each describe block is checked separately. Only hooks that come one right after another are compared. Any other call between two hooks, such as a test, starts a new group.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"jest/prefer-hooks-in-order" = "error" # or "warn"

Examples#

example.ts1 problem
import { afterEach, beforeEach } from "@jest/globals";

afterEach(() => {
  db.rollback();
});

beforeEach(() => {
  db.begin();
});
example.tsNo problems
import { afterEach, beforeEach } from "@jest/globals";

beforeEach(() => {
  db.begin();
});

afterEach(() => {
  db.rollback();
});

The test between these two hooks starts a new group, so this isn't reported. jest/prefer-hooks-on-top reports it instead.

example.tsNo problems
import { afterEach, beforeEach, test } from "@jest/globals";

afterEach(() => {
  db.rollback();
});

test("saves a user", () => {
  db.save(user);
});

beforeEach(() => {
  db.begin();
});