Linter · Rules
jest/prefer-called-with
Require toHaveBeenCalledWith() instead of toHaveBeenCalled()
toHaveBeenCalled() passes no matter what the mock was called with, so the test keeps passing when the code starts passing the wrong arguments. toHaveBeenCalledWith(...) checks the arguments too. The alias toBeCalled() is reported the same way.
.not.toHaveBeenCalled() is allowed, because a mock that never ran has no arguments to check.
--fix renames the matcher and leaves the parentheses empty. Fill in the arguments you expect, because toHaveBeenCalledWith() only passes for a call without arguments.
Configure
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"jest/prefer-called-with" = "error" # or "warn"
Examples
Reported:
import { expect, jest, test } from "@jest/globals";
test("sends a welcome email", () => {
const send = jest.fn();
register("ada@example.com", send);
expect(send).toHaveBeenCalled();
});
Not reported:
import { expect, jest, test } from "@jest/globals";
test("sends a welcome email", () => {
const send = jest.fn();
register("ada@example.com", send);
expect(send).toHaveBeenCalledWith("ada@example.com", "welcome");
});
test("sends nothing for an invalid address", () => {
const send = jest.fn();
register("not an address", send);
expect(send).not.toHaveBeenCalled();
});