Skip to content
← Back to rules

jest/prefer-comparison-matcher 风格

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);

该规则与 eslint-plugin-vitest 兼容。要使用它,请将以下配置添加到你的 .oxlintrc.json 文件中:

json
{
  "rules": {
    "vitest/prefer-comparison-matcher": "error"
  }
}

如何使用

要通过配置文件或 CLI 启用 此规则,可以使用:

json
{
  "plugins": ["jest"],
  "rules": {
    "jest/prefer-comparison-matcher": "error"
  }
}
bash
oxlint --deny jest/prefer-comparison-matcher --jest-plugin

参考资料