vitest/prefer-comparison-matcher Style
它的作用
此规则会检查测试中的比较,是否可以替换为以下内置比较匹配器之一:
toBeGreaterThantoBeGreaterThanOrEqualtoBeLessThantoBeLessThanOrEqual
为什么这不好?
在比较表达式中使用像 toBe(true) 这样的通用匹配器,会降低测试的可读性,并且在失败时提供的信息也不够有帮助。Jest 的特定比较匹配器能更清楚地表达意图,并提供更好的错误输出,显示正在比较的实际值。
示例
以下是此规则的错误代码示例:
js
expect(x > 5).toBe(true);
expect(x < 7).not.toEqual(true);
expect(x <= y).toStrictEqual(true);以下是此规则的正确代码示例:
js
expect(x).toBeGreaterThan(5);
expect(x).not.toBeLessThanOrEqual(7);
expect(x).toBeLessThanOrEqual(y);
// 特殊情况 - 见下文
expect(x < "Carl").toBe(true);如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["vitest"],
"rules": {
"vitest/prefer-comparison-matcher": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["vitest"],
rules: {
"vitest/prefer-comparison-matcher": "error",
},
});bash
oxlint --deny vitest/prefer-comparison-matcher --vitest-plugin版本
此规则于 v0.2.15 中添加。
