Skip to content
← Back to rules

jest/no-done-callback Style

An auto-fix is available for this rule.

它的作用

此规则会检查 hooks 和 tests 的函数参数中是否使用了 done 参数,并建议改为返回一个 promise。

为什么这不好?

在 hooks 和 tests 中调用异步代码时,jest 需要知道异步工作何时完成,才能继续当前运行。 最初,实现这一点最常见的模式是使用回调:

javascript
test("这份数据是花生酱", (done) => {
  function callback(data) {
    try {
      expect(data).toBe("花生酱");
      done();
    } catch (error) {
      done(error);
    }
  }

  fetchData(callback);
});

不过,这很容易出错,因为它要求对断言在测试中的工作方式有细致的理解,否则测试将不会按预期运行。

示例

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

javascript
beforeEach((done) => {
  // ...
});

test("myFunction()", (done) => {
  // ...
});

test("myFunction()", function (done) {
  // ...
});

如何使用

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

json
{
  "plugins": ["jest"],
  "rules": {
    "jest/no-done-callback": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  plugins: ["jest"],
  rules: {
    "jest/no-done-callback": "error",
  },
});
bash
oxlint --deny jest/no-done-callback --jest-plugin

版本

此规则是在 v0.0.13 中添加的。

参考