jest/prefer-mock-return-shorthand 风格
它的作用
在处理返回简单值的函数模拟时,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);该规则与 eslint-plugin-vitest 兼容,
要使用它,请将以下配置添加到您的 .oxlintrc.json 文件中:
json
{
"rules": {
"vitest/prefer-mock-return-shorthand": "error"
}
}如何使用
要通过配置文件或 CLI 启用此规则,可以使用:
json
{
"plugins": ["jest"],
"rules": {
"jest/prefer-mock-return-shorthand": "error"
}
}bash
oxlint --deny jest/prefer-mock-return-shorthand --jest-plugin