Skip to content
← Back to rules

jest/require-hook 风格

它做了什么

此规则会标记测试文件顶层或 describe 块内部的任何表达式,但以下情况除外

  • import 语句
  • const 变量
  • let 声明,以及初始化为 nullundefined 的情况
  • 类型
  • 对标准 Jest 全局函数的调用

为什么这是不好的?

将设置和清理代码放在钩子之外可能导致不可预测的测试行为。在顶层执行的代码会在测试文件加载时运行,而不是在测试运行时,这可能引发测试隔离问题,并使测试依赖于执行顺序。使用正确的钩子(如 beforeEachbeforeAllafterEachafterAll)可以确保设置和清理代码在正确的时间运行,并保持测试的隔离性。

示例

以下为 错误 用法示例:

javascript
import { database, isCity } from "../database";
import { Logger } from "../../../src/Logger";
import { loadCities } from "../api";

jest.mock("../api");

const initializeCityDatabase = () => {
  database.addCity("Vienna");
  database.addCity("San Juan");
  database.addCity("Wellington");
};

const clearCityDatabase = () => {
  database.clear();
};

initializeCityDatabase();

test("that persists cities", () => {
  expect(database.cities.length).toHaveLength(3);
});
test("city database has Vienna", () => {
  expect(isCity("Vienna")).toBeTruthy();
});

test("city database has San Juan", () => {
  expect(isCity("San Juan")).toBeTruthy();
});

describe("when loading cities from the api", () => {
  let consoleWarnSpy = jest.spyOn(console, "warn");
  loadCities.mockResolvedValue(["Wellington", "London"]);

  it("does not duplicate cities", async () => {
    await database.loadCities();
    expect(database.cities).toHaveLength(4);
  });
});
clearCityDatabase();

以下为 正确 用法示例:

javascript
import { database, isCity } from "../database";
import { Logger } from "../../../src/Logger";
import { loadCities } from "../api";

jest.mock("../api");
const initializeCityDatabase = () => {
  database.addCity("Vienna");
  database.addCity("San Juan");
  database.addCity("Wellington");
};

const clearCityDatabase = () => {
  database.clear();
};

beforeEach(() => {
  initializeCityDatabase();
});

test("that persists cities", () => {
  expect(database.cities.length).toHaveLength(3);
});

test("city database has Vienna", () => {
  expect(isCity("Vienna")).toBeTruthy();
});

test("city database has San Juan", () => {
  expect(isCity("San Juan")).toBeTruthy();
});

describe("when loading cities from the api", () => {
  let consoleWarnSpy;
  beforeEach(() => {
    consoleWarnSpy = jest.spyOn(console, "warn");
    loadCities.mockResolvedValue(["Wellington", "London"]);
  });

  it("does not duplicate cities", async () => {
    await database.loadCities();
    expect(database.cities).toHaveLength(4);
  });
});
afterEach(() => {
  clearCityDatabase();
});

此规则与 eslint-plugin-vitest 兼容,要使用它,请在你的 .oxlintrc.json 中添加以下配置:

json
{
  "rules": {
    "vitest/require-hook": "error"
  }
}

配置

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

allowedFunctionCalls

type: string[]

default: []

允许在钩子外部调用的函数名称数组。

如何使用

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

json
{
  "plugins": ["jest"],
  "rules": {
    "jest/require-hook": "error"
  }
}
bash
oxlint --deny jest/require-hook --jest-plugin

参考资料