# jest/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 Jest 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`.

The rule reports two things in those places:

- a statement that's only a function call, such as `setup();`
- a `let` or `var` that starts with a value other than `null` or `undefined`

`const` declarations are allowed. So are calls to `describe`, `test`, `it` and the hooks, and calls on `jest`, such as `jest.mock()`.

The rule checks every file it's turned on for, not only tests. Turn it on for your test files only.

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. To turn it on:

```toml bunfig.toml
[lint.rules]
"jest/require-hook" = "error" # or "warn"
```

Every option, set to its default:

```toml bunfig.toml
[lint.rules]
"jest/require-hook" = ["error", {
  allowedFunctionCalls = [], # list of strings
}]
```

{/* End of the generated section. */}

## Examples

Reported:

{/* bad {"count": 3} */}
```js
import { describe, expect, test } from "@jest/globals";

let db = connect();
db.seed(["ada", "grace"]);

describe("users", () => {
  clearCache();

  test("finds a user", () => {
    expect(db.find("ada")).toBeDefined();
  });
});
```

Not reported:

{/* good */}
```js
import { beforeAll, beforeEach, describe, expect, jest, test } from "@jest/globals";

jest.mock("./mailer");

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 you can call outside a hook. Write a method with its object, like `"expect.extend"`. |

`expect.extend()` and the short forms `fit`, `xit`, `xtest`, `fdescribe` and `xdescribe` are reported unless you list them:

{/* bad {"count": 2} */}
```js
import { expect, xtest } from "@jest/globals";

expect.extend({ toBeUser });

xtest("finds a user", () => {
  expect(db.find("ada")).toBeUser();
});
```

{/* good {"options": [{"allowedFunctionCalls": ["expect.extend", "xtest"]}]} */}
```js
import { expect, xtest } from "@jest/globals";

expect.extend({ toBeUser });

xtest("finds a user", () => {
  expect(db.find("ada")).toBeUser();
});
```
