Skip to content
← Back to rules

jest/no-hooks Style

作用

禁止使用 Jest 的 setup 和 teardown 钩子,例如 beforeAll

为什么这不好?

Jest 提供了用于 setup 和 teardown 任务的全局函数,这些函数会在每个测试用例和每个测试套件之前/之后被调用。使用这些钩子会促进测试之间共享状态。

该规则会对以下函数调用进行报告:

  • beforeAll
  • beforeEach
  • afterAll
  • afterEach

示例

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

javascript
function setupFoo(options) {
  /* ... */
}
function setupBar(options) {
  /* ... */
}

describe("foo", () => {
  let foo;
  beforeEach(() => {
    foo = setupFoo();
  });
  afterEach(() => {
    foo = null;
  });
  it("does something", () => {
    expect(foo.doesSomething()).toBe(true);
  });
  describe("with bar", () => {
    let bar;
    beforeEach(() => {
      bar = setupBar();
    });
    afterEach(() => {
      bar = null;
    });
    it("with bar 做某事", () => {
      expect(foo.doesSomething(bar)).toBe(true);
    });
  });
});

配置

此规则接受一个包含以下属性的配置对象:

allow

type: string[]

default: []

允许使用的钩子函数名称数组。

如何使用

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

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

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

版本

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

参考资料