Skip to content
← Back to rules

vitest/prefer-called-with 样式

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

作用

建议使用 toBeCalledWith()toHaveBeenCalledWith()

为什么这不好?

在测试函数调用时,通常更有价值的是同时断言 函数是否被调用,以及它被调用时传入了哪些参数。 使用 toBeCalled()toHaveBeenCalled() 只能验证函数 被调用了,但不能验证参数,这可能会遗漏 函数以错误参数被调用的 bug。

示例

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

javascript
expect(someFunction).toBeCalled();
expect(someFunction).toHaveBeenCalled();

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

javascript
expect(noArgsFunction).toBeCalledWith();
expect(roughArgsFunction).toBeCalledWith(expect.anything(), expect.any(Date));
expect(anyArgsFunction).toBeCalledTimes(1);
expect(uncalledFunction).not.toBeCalled();

如何使用

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

json
{
  "plugins": ["vitest"],
  "rules": {
    "vitest/prefer-called-with": "error"
  }
}
ts
import { defineConfig } from "oxlint";

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

版本

此规则添加于 v0.2.5。

参考资料