Skip to content
← Back to rules

vitest/no-duplicate-hooks Style

作用

禁止在 describe 块中出现重复的 hooks。

为什么这很糟糕?

在 describe 块中存在重复的 hooks 可能会导致混淆和意外行为。 当同一类型的多个 hooks 存在时,它们都会按顺序执行,这会让人 难以理解测试设置流程,并可能导致冗余或冲突的 操作。这会使测试更难维护和调试。

示例

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

javascript
describe("foo", () => {
  beforeEach(() => {
    // 一些设置
  });
  beforeEach(() => {
    // 一些设置
  });
  test("foo_test", () => {
    // 一些测试
  });
});

// 嵌套 describe 场景
describe("foo", () => {
  beforeEach(() => {
    // 一些设置
  });
  test("foo_test", () => {
    // 一些测试
  });
  describe("bar", () => {
    test("bar_test", () => {
      afterAll(() => {
        // 一些清理
      });
      afterAll(() => {
        // 一些清理
      });
    });
  });
});

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

javascript
describe("foo", () => {
  beforeEach(() => {
    // 一些设置
  });
  test("foo_test", () => {
    // 一些测试
  });
});

// 嵌套 describe 场景
describe("foo", () => {
  beforeEach(() => {
    // 一些设置
  });
  test("foo_test", () => {
    // 一些测试
  });
  describe("bar", () => {
    test("bar_test", () => {
      beforeEach(() => {
        // 一些设置
      });
    });
  });
});

如何使用

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

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

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

版本

此规则在 v0.4.0 中添加。

参考资料