jest/prefer-hooks-on-top 樣式
作用
雖然 Hook 可以在測試檔案中的任何地方設定,但它們總是按照特定的順序被呼叫,這意味著如果它們與測試案例混在一起,可能會造成混淆。
範例
javascript
// invalid
describe("foo", () => {
beforeEach(() => {
seedMyDatabase();
});
it("accepts this input", () => {
// ...
});
beforeAll(() => {
createMyDatabase();
});
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();
});
});
// valid
describe("foo", () => {
beforeAll(() => {
createMyDatabase();
});
beforeEach(() => {
seedMyDatabase();
});
afterAll(() => {
clearMyDatabase();
});
it("accepts this input", () => {
// ...
});
it("returns that value", () => {
// ...
});
describe("when the database has specific values", () => {
const specificValue = "...";
beforeEach(() => {
seedMyDatabase(specificValue);
});
beforeEach(() => {
mockLogger();
});
afterEach(() => {
clearLogger();
});
it("accepts that input", () => {
// ...
});
it("throws an error", () => {
// ...
});
it("logs a message", () => {
// ...
});
});
});