jest/prefer-hooks-on-top 风格
它做了什么
虽然钩子可以在测试文件中的任意位置设置,但它们始终按照特定顺序调用,因此如果将它们与测试用例混合,可能会造成混淆。
为什么这是个问题?
当钩子与测试用例混合时,理解测试设置和执行顺序会变得更加困难。这可能导致对哪些钩子适用于哪些测试以及它们何时运行产生混淆。将钩子集中放在每个 describe 块的顶部,可以使测试结构更清晰且更易于维护。
示例
以下为该规则的 错误 代码示例:
javascript
describe("foo", () => {
beforeEach(() => {
seedMyDatabase();
});
it("接受此输入", () => {
// ...
});
beforeAll(() => {
createMyDatabase();
});
it("返回该值", () => {
// ...
});
describe("当数据库具有特定值时", () => {
const specificValue = "...";
beforeEach(() => {
seedMyDatabase(specificValue);
});
it("接受该输入", () => {
// ...
});
it("抛出错误", () => {
// ...
});
afterEach(() => {
clearLogger();
});
beforeEach(() => {
mockLogger();
});
it("记录消息", () => {
// ...
});
});
afterAll(() => {
removeMyDatabase();
});
});以下为该规则的 正确 代码示例:
javascript
describe("foo", () => {
beforeAll(() => {
createMyDatabase();
});
beforeEach(() => {
seedMyDatabase();
});
afterAll(() => {
clearMyDatabase();
});
it("接受此输入", () => {
// ...
});
it("返回该值", () => {
// ...
});
describe("当数据库具有特定值时", () => {
const specificValue = "...";
beforeEach(() => {
seedMyDatabase(specificValue);
});
beforeEach(() => {
mockLogger();
});
afterEach(() => {
clearLogger();
});
it("接受该输入", () => {
// ...
});
it("抛出错误", () => {
// ...
});
it("记录消息", () => {
// ...
});
});
});此规则与 eslint-plugin-vitest 兼容。要使用它,请在您的 .oxlintrc.json 中添加以下配置:
json
{
"rules": {
"vitest/prefer-hooks-on-top": "error"
}
}如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
json
{
"plugins": ["jest"],
"rules": {
"jest/prefer-hooks-on-top": "error"
}
}bash
oxlint --deny jest/prefer-hooks-on-top --jest-plugin