bun:test/prefer-hooks-on-top

Require hooks to come before the tests in their block

A hook applies to every test in its block, no matter where it's written. A beforeEach below a test still runs before that test, but someone reading from the top hasn't seen it yet.

Each describe block is checked on its own.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"bun:test/prefer-hooks-on-top" = "error" # or "warn"

Examples#

example.ts1 problem
import { beforeEach, expect, test } from "bun:test";

test("starts empty", () => {
  expect(cart.items).toHaveLength(0);
});

beforeEach(() => {
  cart.clear();
});
example.tsNo problems
import { beforeEach, expect, test } from "bun:test";

beforeEach(() => {
  cart.clear();
});

test("starts empty", () => {
  expect(cart.items).toHaveLength(0);
});

A hook at the top of a describe block is fine, even if there's a test before the block:

example.tsNo problems
import { beforeEach, describe, expect, test } from "bun:test";

test("loads the shop", () => {
  expect(shop.ready).toBe(true);
});

describe("cart", () => {
  beforeEach(() => {
    cart.clear();
  });

  test("starts empty", () => {
    expect(cart.items).toHaveLength(0);
  });
});