no-conditional-expect
Configuration
Rule Details
Disallow calling expect conditionally. Jest only marks a test as failed when it throws; if an assertion runs inside a branch that is skipped, the test can pass without exercising the assertion at all. Conditionals also make tests harder to read and reason about. While expect.assertions and expect.hasAssertions can help catch silent skips, combining them with conditionals usually adds even more complexity.
This rule reports expect calls that sit inside conditional control flow, including:
if/elsebranchesswitchcasestry/catchhandlers (including emptycatchblocks that containexpect)- Short-circuit expressions (
&&,||) and ternary expressions whereexpectis on a branch that may not run - Promise
.catch()callbacks whose parameter is treated as an error handler (for example.catch(error => expect(error)...))
The same checks apply when the conditional expect lives in a helper function passed as the test callback. Conditionals that run before an unconditional expect, or that only affect the value passed into expect, are allowed.
Examples of incorrect code for this rule:
Examples of correct code for this rule:
Testing thrown errors without violating this rule
A common pattern is asserting properties on a caught error when toThrow only checks the message. A try / catch with expect in the catch block looks fine but still passes if nothing is thrown:
Prefer a small wrapper that always returns a value (or throws a sentinel when no error occurred), then assert unconditionally: