Skip to content

conditionalExpects

Enforces that expect statements aren't conditionally executed.

✅ This rule is included in the vitest logicalpresets.

Calling expect inside a conditional statement (if, switch, a ternary, &&/||/??, or a catch block) means the assertion may never run. If the condition is never met, the test passes without actually checking anything.

test("something", () => {
if (something) {
expect(something).toBe(true);
}
});
test("something", () => {
something ? expect(something).toBe(true) : null;
});
promise.catch(() => {
expect(true).toBe(false);
});
test("something", () => {
try {
doSomething();
} catch {
expect(true).toBe(false);
}
});
test("something", () => {
switch (something) {
case "a":
expect(something).toBe("a");
break;
}
});
test("something", () => {
something && expect(something).toBe(true);
});

Whether to allow expect calls inside conditionals when the test case calls expect.assertions(...). Defaults to false.

expect.assertions(...) tells Vitest exactly how many assertions the test must run, so a conditional expect that gets skipped will still fail the test for not matching that count.

Examples of correct code with { expectAssertions: true }:

test("something", () => {
expect.assertions(1);
if (something) {
expect(something).toBe(true);
}
});

If your test suite relies on other mechanisms to guarantee conditional assertions still run, such as always calling expect.assertions(...) without opting into the expectAssertions option, this rule might report cases you’ve already accounted for.