jest/prefer-hooks-in-order Style
它的作用
确保 hooks 的顺序与它们被调用的顺序一致。
为什么这不好?
虽然 hooks 可以按任意顺序设置,但 jest 总是按以下特定顺序调用它们:
beforeAllbeforeEachafterEachafterAll
此规则通过强制将分组的 hooks 按照该顺序在测试中设置,来使这一点更加明显。
示例
以下是此规则的错误代码示例:
javascript
describe("foo", () => {
beforeEach(() => {
seedMyDatabase();
});
beforeAll(() => {
createMyDatabase();
});
it("accepts this input", () => {
// ...
});
it("returns that value", () => {
// ...
});
describe("when the database has specific values", () => {
const specificValue = "...";
beforeEach(() => {
seedMyDatabase(specificValue);
});
it("accepts that input", () => {
// ...
});
it("throws an error", () => {
// ...
});
afterEach(() => {
clearLogger();
});
beforeEach(() => {
mockLogger();
});
it("logs a message", () => {
// ...
});
});
afterAll(() => {
removeMyDatabase();
});
});以下是此规则的正确代码示例:
javascript
describe("foo", () => {
beforeAll(() => {
createMyDatabase();
});
beforeEach(() => {
seedMyDatabase();
});
it("accepts this input", () => {
// ...
});
it("returns that value", () => {
// ...
});
describe("when the database has specific values", () => {
const specificValue = "...";
beforeEach(() => {
seedMyDatabase(specificValue);
});
it("accepts that input", () => {
// ...
});
it("throws an error", () => {
// ...
});
beforeEach(() => {
mockLogger();
});
afterEach(() => {
clearLogger();
});
it("logs a message", () => {
// ...
});
});
afterAll(() => {
removeMyDatabase();
});
});How to use
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["jest"],
"rules": {
"jest/prefer-hooks-in-order": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["jest"],
rules: {
"jest/prefer-hooks-in-order": "error",
},
});bash
oxlint --deny jest/prefer-hooks-in-order --jest-plugin版本
此规则在 v0.6.0 中添加。
