jest/require-to-throw-message
Require toThrow() to say which error it expects
toThrow() without an argument passes for any error at all, including a TypeError from a typo in the code under test. The test stays green even though the code never reached the check you meant to test. Pass part of the message, a regular expression, or the error class.
.not.toThrow() is allowed, because there's no error to describe.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"jest/require-to-throw-message" = "error" # or "warn"Examples#
example.js3 problems
import { expect, test } from "@jest/globals";
test("rejects a negative amount", async () => {
expect(() => withdraw(-5)).toThrowRequire a message for toThrow.();
expect(() => withdraw(-5)).toThrowErrorRequire a message for toThrowError.();
await expect(transfer(-5)).rejects.toThrowRequire a message for toThrow.();
});example.jsNo problems
import { expect, test } from "@jest/globals";
test("rejects a negative amount", async () => {
expect(() => withdraw(-5)).toThrow("amount must be positive");
expect(() => withdraw(-5)).toThrow(RangeError);
await expect(transfer(-5)).rejects.toThrow(/positive/);
});
test("accepts a positive amount", () => {
expect(() => withdraw(5)).not.toThrow();
});