jest/no-conditional-in-test

Disallow if, switch, ? :, &&, || and ?? inside a test

A test with a branch in it checks different things on different runs. When it fails, you first have to find out which path it took, and a path that's never taken is never tested. The branch often repeats the logic of the code under test, mistakes included.

Write one test for each case, or a table of cases with test.each. Conditions outside a test aren't reported.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"jest/no-conditional-in-test" = "error" # or "warn"

Examples#

example.ts1 problem
import { expect, test } from "@jest/globals";
import { label, users } from "./users";

test("labels every user", () => {
  for (const user of users) {
    const expected = user.admin ? "Admin" : "Member";
    expect(label(user)).toBe(expected);
  }
});
example.tsNo problems
import { expect, test } from "@jest/globals";
import { label } from "./users";

test.each([
  [true, "Admin"],
  [false, "Member"],
])("labels a user with admin: %s", (admin, expected) => {
  expect(label({ admin })).toBe(expected);
});
example.ts1 problem
import { expect, test } from "@jest/globals";
import { homeDirectory } from "./paths";

test("finds the home directory", () => {
  if (process.platform === "win32") {
    expect(homeDirectory()).toMatch(/^C:/);
  } else {
    expect(homeDirectory()).toMatch(/^\//);
  }
});

Not reported, because the condition decides which test runs and isn't inside one:

example.tsNo problems
import { expect, test } from "@jest/globals";
import { homeDirectory } from "./paths";

const onWindows = process.platform === "win32" ? test : test.skip;

onWindows("finds the home directory", () => {
  expect(homeDirectory()).toMatch(/^C:/);
});

When not to use it#

If you're fine with a condition in a test as long as every expect runs, use jest/no-conditional-expect instead.