jest/prefer-called-with 风格
它的作用
建议使用 toBeCalledWith() 或 toHaveBeenCalledWith()
为什么这是个问题?
在测试函数调用时,通常更有价值的是同时断言:
- 函数被调用了,
- 以及它被调用时所使用的参数。
使用 toBeCalled() 或 toHaveBeenCalled() 只验证了函数是否被调用,但并未验证参数是否正确,可能导致遗漏因函数以错误参数被调用而引发的潜在缺陷。
示例
此规则的 错误 代码示例:
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();该规则与 eslint-plugin-vitest 兼容。要使用它,请在你的 .oxlintrc.json 中添加以下配置:
json
{
"rules": {
"vitest/prefer-called-with": "error"
}
}如何使用
通过配置文件或 CLI 启用此规则的方法如下:
json
{
"plugins": ["jest"],
"rules": {
"jest/prefer-called-with": "error"
}
}bash
oxlint --deny jest/prefer-called-with --jest-plugin