Skip to content
← Back to rules

jest/prefer-expect-resolves 风格

An auto-fix is available for this rule.

它的作用

在测试异步函数时,优先使用 await expect(...).resolves 而非 expect(await ...)

为什么这是不好的?

在处理异步函数时,有两种主要方式可以测试其解析后的值:

  1. expect 上使用 resolve 修饰符(await expect(...).resolves.<matcher> 风格)
  2. 使用 await 等待异步函数并断言其结果(expect(await ...).<matcher> 风格)

虽然第二种风格在某种程度上对 Jest 的依赖较少,但当异步函数拒绝(reject)时,它会被当作一个普通错误处理,从而导致 Jest 的行为和输出不可预测。

此外,优先使用第一种风格有助于与 rejects 对应风格保持一致,因为无法“等待”一个拒绝状态。

示例

此规则的错误代码示例:

javascript
it("通过", async () => {
  expect(await someValue()).toBe(true);
});
it("为真", async () => {
  const myPromise = Promise.resolve(true);
  expect(await myPromise).toBe(true);
});

此规则的正确代码示例:

javascript
it("通过", async () => {
  await expect(someValue()).resolves.toBe(true);
});
it("为真", async () => {
  const myPromise = Promise.resolve(true);

  await expect(myPromise).resolves.toBe(true);
});
it("报错", async () => {
  await expect(Promise.reject(new Error("哦不!"))).rejects.toThrowError("哦不!");
});

该规则与 eslint-plugin-vitest 兼容。要使用它,请将以下配置添加到你的 .oxlintrc.json 文件中:

json
{
  "rules": {
    "vitest/prefer-expect-resolves": "error"
  }
}

如何使用

要通过配置文件或 CLI 启用此规则,可以使用:

json
{
  "plugins": ["jest"],
  "rules": {
    "jest/prefer-expect-resolves": "error"
  }
}
bash
oxlint --deny jest/prefer-expect-resolves --jest-plugin

参考资料