jest/prefer-to-have-been-called-times 风格
它的作用
为了获得更好的错误信息,应使用 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);如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
json
{
"plugins": ["jest"],
"rules": {
"jest/prefer-to-have-been-called-times": "error"
}
}bash
oxlint --deny jest/prefer-to-have-been-called-times --jest-plugin