Skip to content
← Back to rules

jest/prefer-to-have-been-called-times Style

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

作用

为了获得更好的失败信息,应该使用 toHaveBeenCalledTimes 而不是直接检查 mock.calls 的长度

为什么这不好?

如果使用 toHaveLength 来断言 mock 被调用的次数,此规则会触发警告。

示例

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

js
expect(someFunction.mock.calls).toHaveLength(1);
expect(someFunction.mock.calls).toHaveLength(0);
expect(someFunction.mock.calls).not.toHaveLength(1);

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

js
expect(someFunction).toHaveBeenCalledTimes(1);
expect(someFunction).toHaveBeenCalledTimes(0);
expect(someFunction).not.toHaveBeenCalledTimes(0);
expect(uncalledFunction).not.toBeCalled();
expect(method.mock.calls[0][0]).toStrictEqual(value);

如何使用

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

json
{
  "plugins": ["jest"],
  "rules": {
    "jest/prefer-to-have-been-called-times": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  plugins: ["jest"],
  rules: {
    "jest/prefer-to-have-been-called-times": "error",
  },
});
bash
oxlint --deny jest/prefer-to-have-been-called-times --jest-plugin

版本

此规则在 v1.34.0 中添加。

参考