require-hook
Configuration
Rule Details
Require setup and teardown code to be within a Jest lifecycle hook (beforeEach, afterEach, beforeAll, afterAll).
It's common when writing tests to need setup work before tests run and cleanup afterward. Because Jest executes all describe handlers in a test file before any of the actual tests, setup and teardown done directly in a describe body (or at the top level of the file) can run at the wrong time or leak across suites. This rule pushes that work into the lifecycle hooks instead.
This rule checks direct statements at the top level of a test file and direct statements within the body of each describe callback. It does not inspect arbitrary statements nested inside control-flow statements or other function callbacks.
It flags expressions in those scopes except for:
importstatementsconstvariable declarations, including declarations with initializers- Uninitialized
letandvardeclarations letandvardeclarations initialized directly withnullorundefined- Classes
- Types
- Calls to recognized Jest APIs, such as
describe,test/it, lifecycle hooks,expect, andjest.*
For variable declarations, a declaration containing any other initializer is reported as a whole. For example:
Examples of incorrect code for this rule:
Examples of correct code for this rule:
Options
- First argument (optional): object with
allowedFunctionCallsallowedFunctionCalls: array of exact callee names that are allowed outside hooks. Names are matched against the full dotted callee name, sohelper.setupmatcheshelper.setup()butsetupdoes not.