Skip to content
← Back to rules

jest/prefer-mock-promise-shorthand Style

🛠️ An auto-fix is available for this rule for some violations.

它的作用

在处理返回 promise 的函数的 mock 时,Jest 提供了一些 API 语法糖函数,用于减少你需要编写的样板代码量。在可能的情况下,应优先使用这些方法。

为什么这不好?

使用诸如 mockImplementation(() => Promise.resolve())mockReturnValue(Promise.reject()) 之类的通用 mock 函数,比起 Jest 专门用于 promise 的简写方法,更冗长、可读性更差。像 mockResolvedValue()mockRejectedValue() 这样的简写方法表达力更强,也能让测试意图更清晰。

示例

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

javascript
jest.fn().mockImplementation(() => Promise.resolve(123));
jest.spyOn(fs.promises, "readFile").mockReturnValue(Promise.reject(new Error("哦不!")));

myFunction
  .mockReturnValueOnce(Promise.resolve(42))
  .mockImplementationOnce(() => Promise.resolve(42))
  .mockReturnValue(Promise.reject(new Error("调用太多次了!")));

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

javascript
jest.fn().mockResolvedValue(123);
jest.spyOn(fs.promises, "readFile").mockRejectedValue(new Error("哦不!"));

myFunction
  .mockResolvedValueOnce(42)
  .mockResolvedValueOnce(42)
  .mockRejectedValue(new Error("调用太多次了!"));

How to use

To enable this rule using the config file or in the CLI, you can use:

json
{
  "plugins": ["jest"],
  "rules": {
    "jest/prefer-mock-promise-shorthand": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  plugins: ["jest"],
  rules: {
    "jest/prefer-mock-promise-shorthand": "error",
  },
});
bash
oxlint --deny jest/prefer-mock-promise-shorthand --jest-plugin

版本

此规则自 v0.2.16 起添加。

参考资料