jest/no-restricted-matchers

Disallow the matchers and modifiers you list

Some matchers are too loose for your tests. toBeTruthy() passes for 1, "no" and [], so it doesn't prove that a value is true. This rule reports the matchers and modifiers you list.

Without options it reports nothing.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"jest/no-restricted-matchers" = "error" # or "warn"

Examples#

Both examples use { "toBeTruthy": "Use toBe(true) instead" }.

example.tswith { "toBeTruthy": "Use toBe(true) instead" }1 problem
import { expect, test } from "@jest/globals";

test("a new user is active", () => {
  const user = { active: true };
  expect(user.active).toBeTruthy();
});
example.tswith { "toBeTruthy": "Use toBe(true) instead" }No problems
import { expect, test } from "@jest/globals";

test("a new user is active", () => {
  const user = { active: true };
  expect(user.active).toBe(true);
});

Options#

The rule takes one object. Each key is the chain you write after expect(..), joined with dots. Each value is a hint shown with the report, or null for no hint.

{
  "rules": {
    "jest/no-restricted-matchers": [
      "error",
      {
        "toBeTruthy": "Use toBe(true) instead",
        "not.toHaveBeenCalledWith": null,
        "resolves": "Await the promise, then check the value"
      }
    ]
  }
}
KeyWhat it reports
A matcher, such as "toBe"expect(a).toBe(b), but not expect(a).not.toBe(b).
A chain, such as "not.toBe"expect(a).not.toBe(b), but not expect(a).toBe(b).
"not", "resolves", "rejects", or a chain that ends in .not, such as "resolves.not"Every chain that starts with it.

A matcher must be the whole chain, so "toBe" allows this:

example.tswith { "toBe": null }No problems
import { expect, test } from "@jest/globals";

test("ids differ", () => {
  expect(createId()).not.toBe(createId());
});

A modifier matches no matter what comes after it:

example.tswith { "resolves": null }2 problems
import { expect, test } from "@jest/globals";

test("loads the user", async () => {
  await expect(loadUser(1)).resolves.toEqual({ id: 1 });
  await expect(loadUser(2)).resolves.not.toBeNull();
});