Skip to content
← Back to rules

vitest/prefer-to-be-truthy Style

💡 A suggestion is available for this rule.

作用 ​

当 expect 或 expectTypeOf 使用 toBe(true) 时,此规则会发出警告。 使用 --fix-suggestions 时,它会被替换为 toBeTruthy()。

为什么这不好? ​

测试真值时,toBeTruthy() 能直接表达这一意图。 与 toBe(true) 不同,它还接受非空字符串和对象等非布尔真值。由于替换会改变断言通过的值,因此它被作为建议提供。

示例 ​

此规则的错误代码示例:

javascript
expect(foo).toBe(true);
expectTypeOf(foo).toBe(true);

此规则的正确代码示例:

javascript
expect(foo).toBeTruthy();
expectTypeOf(foo).toBeTruthy();

如何使用 ​

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

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

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

版本 ​

此规则在 v0.7.1 中加入。

参考资料 ​