vitest/prefer-mock-return-shorthand Style
作用
在处理返回简单值的函数 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);如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["vitest"],
"rules": {
"vitest/prefer-mock-return-shorthand": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["vitest"],
rules: {
"vitest/prefer-mock-return-shorthand": "error",
},
});bash
oxlint --deny vitest/prefer-mock-return-shorthand --vitest-plugin版本
此规则于 v1.49.0 中添加。
