---
url: /docs/guide/usage/linter/rules/vitest/prefer-mock-return-shorthand.md
---

### 作用

在处理返回简单值的函数 mock 时，Jest 提供了一些 API 语法糖函数，以减少你需要编写的样板代码。

### 为什么这不好？

不使用 Jest 的 API 语法糖函数会增加不必要的样板代码，并使测试更难阅读。这些辅助函数能够清晰表达意图，并减少错误，让测试保持简单且易于维护。

### 示例

以下是此规则的**错误**代码示例：

```js
jest.fn().mockImplementation(() => "hello world");

jest
  .spyOn(fs.promises, "readFile")
  .mockImplementationOnce(() => Promise.reject(new Error("oh noes!")));

myFunction
  .mockImplementationOnce(() => 42)
  .mockImplementationOnce(() => Promise.resolve(42))
  .mockReturnValue(0);
```

以下是此规则的**正确**代码示例：

```js
jest.fn().mockResolvedValue(123);

jest.spyOn(fs.promises, "readFile").mockReturnValue(Promise.reject(new Error("oh noes!")));
jest.spyOn(fs.promises, "readFile").mockRejectedValue(new Error("oh noes!"));

jest.spyOn(fs, "readFileSync").mockImplementationOnce(() => {
  throw new Error("oh noes!");
});

myFunction.mockResolvedValueOnce(42).mockResolvedValueOnce(42).mockReturnValue(0);
```

## 如何使用

## 版本

此规则于 v1.49.0 中添加。

## 参考资料
