jest/prefer-mock-return-shorthand

Require mockReturnValue() for a mock that only returns a value

fixable

mockImplementation(() => value) wraps a value in a function that only returns it. mockReturnValue(value) does the same thing with less code. The same goes for mockImplementationOnce() and mockReturnValueOnce().

--fix rewrites the call.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"jest/prefer-mock-return-shorthand" = "error" # or "warn"

Examples#

example.ts2 problems
import { jest } from "@jest/globals";

const getPort = jest.fn().mockImplementation(() => 3000);

const getUser = jest.fn().mockImplementationOnce(() => {
  return { name: "Ada" };
});
example.tsNo problems
import { jest } from "@jest/globals";

const getPort = jest.fn().mockReturnValue(3000);

const getUser = jest.fn().mockReturnValueOnce({ name: "Ada" });

A function that takes parameters, is async, does more than return, or returns a let or var variable needs mockImplementation(), so it isn't reported:

example.tsNo problems
import { jest } from "@jest/globals";

let visits = 0;

const double = jest.fn().mockImplementation((n: number) => n * 2);
const load = jest.fn().mockImplementation(async () => "done");
const countVisits = jest.fn().mockImplementation(() => visits);
const nextVisit = jest.fn().mockImplementation(() => {
  visits += 1;
  return "ok";
});

A function that returns the result of a call or a new is reported, but --fix leaves it alone. mockReturnValue(createUser()) calls createUser() once, not each time the mock is called.

example.ts1 problem
import { jest } from "@jest/globals";

const getUser = jest.fn().mockImplementation(() => createUser());

When not to use it#

mockReturnValue({ name: "Ada" }) returns the same object on every call. mockImplementation(() => ({ name: "Ada" })) returns a new one. If the code under test mutates the object the mock returns, keep the function and disable the rule on that line.