Skip to content
← Back to rules

jest/prefer-expect-resolves Style

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

它的作用

在测试 promise 时,优先使用 await expect(...).resolves,而不是 expect(await ...)

为什么这不好?

在处理 promise 时,有两种主要方式可以测试其 resolved 值:

  1. expect 上使用 resolve 修饰符 (await expect(...).resolves.<matcher> 风格)
  2. 对 promise 使用 await,并断言其结果 (expect(await ...).<matcher> 风格)

虽然第二种风格在一定程度上不那么依赖 jest,但如果 promise 被 reject,它会被当作一般错误处理,从而导致 jest 的行为和输出不够可预测。

此外,偏向第一种风格还能与其 rejects 对应项保持一致,因为不存在“await 一个 rejection”的方式。

示例

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

javascript
it("passes", async () => {
  expect(await someValue()).toBe(true);
});
it("is true", async () => {
  const myPromise = Promise.resolve(true);
  expect(await myPromise).toBe(true);
});

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

javascript
it("passes", async () => {
  await expect(someValue()).resolves.toBe(true);
});
it("is true", async () => {
  const myPromise = Promise.resolve(true);

  await expect(myPromise).resolves.toBe(true);
});
it("errors", async () => {
  await expect(Promise.reject(new Error("oh noes!"))).rejects.toThrowError("oh noes!");
});

如何使用

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

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

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

版本

此规则于 v0.2.14 中添加。

参考