Skip to content
← Back to rules

jest/prefer-mock-promise-shorthand 风格

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

它做了什么

在处理返回 Promise 的函数的模拟时,Jest 提供了一些 API 便捷方法,以减少你需要编写的样板代码量。在可能的情况下应优先使用这些方法。

为什么这是不好的?

使用通用的模拟函数,如 mockImplementation(() => Promise.resolve())mockReturnValue(Promise.reject()),比 Jest 的专用 Promise 快捷方法更加冗长且可读性差。快捷方法如 mockResolvedValue()mockRejectedValue() 更具表现力,能更清晰地表达测试意图。

示例

此规则的错误代码示例:

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

myFunction
  .mockReturnValueOnce(Promise.resolve(42))
  .mockImplementationOnce(() => Promise.resolve(42))
  .mockReturnValue(Promise.reject(new Error("too many calls!")));

此规则的正确代码示例:

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

myFunction
  .mockResolvedValueOnce(42)
  .mockResolvedValueOnce(42)
  .mockRejectedValue(new Error("too many calls!"));

此规则与 eslint-plugin-vitest 兼容。要使用它,请将以下配置添加到你的 .oxlintrc.json 文件中:

json
{
  "rules": {
    "vitest/prefer-mock-promise-shorthand": "error"
  }
}

如何使用

要通过配置文件或 CLI 启用此规则,可以使用:

json
{
  "plugins": ["jest"],
  "rules": {
    "jest/prefer-mock-promise-shorthand": "error"
  }
}
bash
oxlint --deny jest/prefer-mock-promise-shorthand --jest-plugin

参考资料