Skip to content
← Back to rules

jest/prefer-spy-on Style

💡 A suggestion is available for this rule.

它的作用

当通过覆盖属性来模拟函数时,在清理时你必须手动恢复原始实现。使用 jest.spyOn() 时,Jest 会跟踪这些变更,并且可以通过 jest.restoreAllMocks()mockFn.mockRestore() 或在 Jest 配置中将 restoreMocks 设为 true 来恢复。

注意:jest.spyOn() 创建的 mock 仍然与原始函数表现相同。原始函数可以通过 mockFn.mockImplementation() 或其他一些 模拟函数 来覆盖。

为什么这很糟糕?

直接用 mock 函数覆盖属性会导致清理问题和测试隔离问题。当你手动将 mock 赋值给某个属性时,你需要负责恢复原始实现,这很容易忘记,并且可能导致测试相互干扰。使用 jest.spyOn() 提供了自动清理能力,并使你的测试更加可靠。

示例

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

javascript
Date.now = jest.fn();
Date.now = jest.fn(() => 10);

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

javascript
jest.spyOn(Date, "now");
jest.spyOn(Date, "now").mockImplementation(() => 10);

如何使用

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

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

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

版本

此规则于 v0.2.14 中添加。

参考