vitest/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 doesn't report anything.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"vitest/no-restricted-matchers" = "error" # or "warn"Examples#
Both examples use { "toBeTruthy": "Use toBe(true) instead" }.
example.tswith
{ "toBeTruthy": "Use toBe(true) instead" }1 problemimport { expect, test } from "vitest";
test("a new user is active", () => {
const user = { active: true };
expect(user.active).toBeTruthyUse of toBeTruthy is disallowed();
});example.tswith
{ "toBeTruthy": "Use toBe(true) instead" }No problemsimport { expect, test } from "vitest";
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": {
"vitest/no-restricted-matchers": [
"error",
{
"toBeTruthy": "Use toBe(true) instead",
"not.toHaveBeenCalledWith": null,
"resolves": "Await the promise, then check the value"
}
]
}
}| Key | What 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 problemsimport { expect, test } from "vitest";
test("ids differ", () => {
expect(createId()).not.toBe(createId());
});A modifier matches whatever comes after it:
example.tswith
{ "resolves": null }2 problemsimport { expect, test } from "vitest";
test("loads the user", async () => {
await expect(loadUser(1)).resolves.toEqualUse of resolves.toEqual is disallowed({ id: 1 });
await expect(loadUser(2)).resolves.not.toBeNullUse of resolves.not.toBeNull is disallowed();
});