Skip to content
← Back to rules

vitest/prefer-to-have-length Style

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

作用

为了获得更好的失败信息,在断言对象的 length 属性时,应使用 toHaveLength()

为什么这不好?

当使用 toBe()toEqual()toStrictEqual() 来断言对象的 length 属性时,此规则会触发警告。

示例

以下是此规则的错误代码示例:

javascript
expect(files["length"]).toBe(1);
expect(files["length"]).toBe(1);
expect(files["length"])["not"].toBe(1);

以下是此规则的正确代码示例:

javascript
expect(files).toHaveLength(1);

如何使用

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

json
{
  "plugins": ["vitest"],
  "rules": {
    "vitest/prefer-to-have-length": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  plugins: ["vitest"],
  rules: {
    "vitest/prefer-to-have-length": "error",
  },
});
bash
oxlint --deny vitest/prefer-to-have-length --vitest-plugin

版本

此规则于 v0.2.13 中添加。

参考资料