Skip to content
← Back to rules

jest/prefer-comparison-matcher Style

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

作用

此规则会检查测试中的比较,看看它们是否可以替换为以下内置比较匹配器之一:

  • toBeGreaterThan
  • toBeGreaterThanOrEqual
  • toBeLessThan
  • toBeLessThanOrEqual

为什么这不好?

在比较表达式中使用像 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);

How to use

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

json
{
  "plugins": ["jest"],
  "rules": {
    "jest/prefer-comparison-matcher": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  plugins: ["jest"],
  rules: {
    "jest/prefer-comparison-matcher": "error",
  },
});
bash
oxlint --deny jest/prefer-comparison-matcher --jest-plugin

版本

此规则于 v0.2.15 中添加。

参考