vitest/prefer-expect-type-of 风格
它的作用
强制使用 expectTypeOf 代替 expect(typeof ...)
为什么这是不好的?
Vitest 提供了一种比使用 expect(typeof ...) 更具表现力且类型安全的测试方式。
示例
此规则的 错误 代码示例:
js
test('类型检查', () => {
expect(typeof 'hello').toBe('string')
expect(typeof 42).toBe('number')
expect(typeof true).toBe('boolean')
expect(typeof {}).toBe('object')
expect(typeof () => {}).toBe('function')
expect(typeof Symbol()).toBe('symbol')
expect(typeof 123n).toBe('bigint')
expect(typeof undefined).toBe('undefined')
})此规则的 正确 代码示例:
js
test("类型检查", () => {
expectTypeOf("hello").toBeString();
expectTypeOf(42).toBeNumber();
expectTypeOf(true).toBeBoolean();
expectTypeOf({}).toBeObject();
expectTypeOf(() => {}).toBeFunction();
expectTypeOf(Symbol()).toBeSymbol();
expectTypeOf(123n).toBeBigInt();
expectTypeOf(undefined).toBeUndefined();
});如何使用
要通过配置文件或 CLI 启用此规则,可以使用:
json
{
"plugins": ["vitest"],
"rules": {
"vitest/prefer-expect-type-of": "error"
}
}bash
oxlint --deny vitest/prefer-expect-type-of --vitest-plugin