jest/prefer-hooks-in-order 樣式
作用
雖然 hooks 可以以任何順序設定,但它們總是按照這個特定順序被 jest
呼叫
beforeAll
beforeEach
afterEach
afterAll
此規則旨在透過強制在測試中以該順序設定分組的 hooks 來使這一點更明顯。
範例
javascript
// invalid
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
// valid
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();
});
});
此規則與 eslint-plugin-vitest 相容,要使用它,請將以下設定新增至您的 .eslintrc.json
json
{
"rules": {
"vitest/prefer-hooks-in-order": "error"
}
}
## References
- [Rule Source](https://github.com/oxc-project/oxc/blob/main/crates/oxc_linter/src/rules/jest/prefer_hooks_in_order.rs)