首页 > 解决方案 > In what order does beforeEach and beforeAll execute?

问题描述

I'm using Jest-Puppeteer to end2end test a Rails application. Before these tests I want to run some seeds and to work DRY I tell the server to go to a certain URL before each test.

// imports

describe("user can", () => {
  // here are some constants

  let page;

  beforeAll(async () => {
    await executeSeed(const1);
    await executeSeed(const2);
    await executeSeed(const3);

    page = await newPrivatePage();
    await login(page);
  });

  beforeEach(async () => {
    await page.goto(baseUrl("/some-route"));
  });

  describe("view some great files", () => {

});

I'd expect the seeds to be executed first, since this is beforeAll and if the first test finishes the beforeEach will be done again, but I can't find it in the documentation of jest (https://jestjs.io/docs/en/api#beforeallfn-timeout)

标签: testingjestjs

解决方案


你可以阅读这篇关于 Jest 文档的文章https://jestjs.io/docs/en/setup-teardown.html 。

beforeAll(() => console.log('1 - beforeAll'));
afterAll(() => console.log('1 - afterAll'));
beforeEach(() => console.log('1 - beforeEach'));
afterEach(() => console.log('1 - afterEach'));
test('', () => console.log('1 - test'));
describe('Scoped / Nested block', () => {
  beforeAll(() => console.log('2 - beforeAll'));
  afterAll(() => console.log('2 - afterAll'));
  beforeEach(() => console.log('2 - beforeEach'));
  afterEach(() => console.log('2 - afterEach'));
  test('', () => console.log('2 - test'));
});

// 1 - beforeAll
// 1 - beforeEach
// 1 - test
// 1 - afterEach
// 2 - beforeAll
// 1 - beforeEach
// 2 - beforeEach
// 2 - test
// 2 - afterEach
// 1 - afterEach
// 2 - afterAll
// 1 - afterAll

如您所见,beforeAll将在执行所有测试之前运行。beforeEach将在你们每个人测试之前运行。所以beforeAll会在之前运行beforeEach


推荐阅读