Skip to content
← Back to rules

vitest/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("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!"));

如何使用

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

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

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

版本

此规则于 v0.2.16 中添加。

参考资料