jest/no-restricted-matchers 风格
功能说明
禁止使用特定的匹配器和修饰符,并可提供替代方案建议。
为什么这是不好的?
由于各种原因,某些匹配器或修饰符可能在你的代码库中被不推荐使用: 它们可能已被弃用、容易引起混淆、存在性能问题,或者已有更好的替代方案。此规则允许你通过限制某些 Jest 匹配器并提供首选替代方案的指导,来强制执行一致的测试模式。
示例
禁止项以映射表的形式表达,值可以是显示的字符串消息,也可以为 null(仅使用默认规则消息)。检查从 expect 链的起始位置进行——这意味着要完全禁止某个特定匹配器,必须指定全部六种排列组合,但这也允许你禁止修饰符。默认情况下,该映射为空,表示没有匹配器或修饰符被禁止。
示例配置:
json
{
"jest/no-restricted-matchers": [
"error",
{
"toBeFalsy": null,
"resolves": "改用 `expect(await promise)`。",
"toHaveBeenCalledWith": null,
"not.toHaveBeenCalledWith": null,
"resolves.toHaveBeenCalledWith": null,
"rejects.toHaveBeenCalledWith": null,
"resolves.not.toHaveBeenCalledWith": null,
"rejects.not.toHaveBeenCalledWith": null
}
]
}以下为 错误 的代码示例(使用上述配置):
javascript
it("为假", () => {
// 如果带有修饰符(如 `not.toBeFalsy`),则被视为合法
expect(a).toBeFalsy();
});
it("会解析", async () => {
// 所有此修饰符的使用均被禁止,与匹配器无关
await expect(myPromise()).resolves.toBe(true);
});
describe("当发生错误时", () => {
it("不会上传文件", async () => {
// 所有此匹配器的使用均被禁止
expect(uploadFileMock).not.toHaveBeenCalledWith("file.name");
});
});该规则与 eslint-plugin-vitest 兼容。要使用它,请将以下配置添加到你的 .oxlintrc.json 文件中:
json
{
"rules": {
"vitest/no-restricted-matchers": "error"
}
}配置
此规则接受一个包含以下属性的配置对象:
restrictedMatchers
type: Record<string, string>
default: {}
受限制的匹配器/修饰符到自定义消息的映射。 键为匹配器/修饰符名称(例如:"toBeFalsy"、"resolves"、"not.toHaveBeenCalledWith")。 值为可选的自定义消息,在使用该匹配器/修饰符时显示。
如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
json
{
"plugins": ["jest"],
"rules": {
"jest/no-restricted-matchers": "error"
}
}bash
oxlint --deny jest/no-restricted-matchers --jest-plugin