Skip to content
← Back to rules

jest/valid-expect-in-promise 正确性

作用

确保 promise 链(.then().catch().finally())中的 expect 调用被正确地 await 或从测试中返回。

这为什么不好?

当在一个没有被 await 或返回的 promise 回调中调用 expect 时,即使断言失败,测试也可能通过,因为在 promise 解析之前测试就已经结束了。这会导致带有错误断言的测试静默通过。

示例

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

javascript
test("promise test", async () => {
  something().then((value) => {
    expect(value).toBe("red");
  });
});

test("promises test", () => {
  const onePromise = something().then((value) => {
    expect(value).toBe("red");
  });
  const twoPromise = something().then((value) => {
    expect(value).toBe("blue");
  });

  return Promise.any([onePromise, twoPromise]);
});

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

javascript
test("promise test", async () => {
  await something().then((value) => {
    expect(value).toBe("red");
  });
});

test("promises test", () => {
  const onePromise = something().then((value) => {
    expect(value).toBe("red");
  });
  const twoPromise = something().then((value) => {
    expect(value).toBe("blue");
  });

  return Promise.all([onePromise, twoPromise]);
});

如何使用

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

json
{
  "plugins": ["jest"],
  "rules": {
    "jest/valid-expect-in-promise": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  plugins: ["jest"],
  rules: {
    "jest/valid-expect-in-promise": "error",
  },
});
bash
oxlint --deny jest/valid-expect-in-promise --jest-plugin

版本

此规则于 v1.60.0 中添加。

参考资料