Skip to content
← Back to rules

vitest/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": ["vitest"],
  "rules": {
    "vitest/prefer-to-have-been-called-times": "error"
  }
}
ts
import { defineConfig } from "oxlint";

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

版本

此规则已在 v1.34.0 中添加。

参考资料