jest/no-conditional-expect Correctness
作用
此规则禁止在条件块中使用 expect,例如 if 和 catch。 这包括在名为 catch 的函数回调中使用 expect,这些函数通常被认为是 promise。
为什么这不好?
Jest 只会在测试抛出错误时才认为测试失败,这意味着如果像 expect 这样的断言函数调用出现在 catch 语句之类的条件代码中, 测试最终可能会通过,但实际上并没有真正测试任何东西。此外,条件判断 往往会让测试更加脆弱和复杂,因为它们会增加理解实际测试内容所需的思考量。
示例
以下是此规则的错误代码示例:
js
it("foo", () => {
doTest && expect(1).toBe(2);
});
it("bar", () => {
if (!skipTest) {
expect(1).toEqual(2);
}
});
it("baz", async () => {
try {
await foo();
} catch (err) {
expect(err).toMatchObject({ code: "MODULE_NOT_FOUND" });
}
});
it("throws an error", async () => {
await foo().catch((error) => expect(error).toBeInstanceOf(error));
});以下是此规则的正确代码示例:
js
it("foo", () => {
expect(!value).toBe(false);
});
function getValue() {
if (process.env.FAIL) {
return 1;
}
return 2;
}
it("foo", () => {
expect(getValue()).toBe(2);
});
it("validates the request", () => {
try {
processRequest(request);
} catch {
} finally {
expect(validRequest).toHaveBeenCalledWith(request);
}
});
it("throws an error", async () => {
await expect(foo).rejects.toThrow(Error);
});如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["jest"],
"rules": {
"jest/no-conditional-expect": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["jest"],
rules: {
"jest/no-conditional-expect": "error",
},
});bash
oxlint --deny jest/no-conditional-expect --jest-plugin版本
此规则在 v0.0.12 中添加。
