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", () => {
// ...
});
});
});