Search code examples
testingjestjs

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 there 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)


Solution

  • You can read this article https://jestjs.io/docs/en/setup-teardown.html on Jest document.

    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'));
    });
    
    // Execution order
    // 1 - beforeAll
    // 1 - beforeEach
    // 1 - test
    // 1 - afterEach
    // 2 - beforeAll
    // 1 - beforeEach
    // 2 - beforeEach
    // 2 - test
    // 2 - afterEach
    // 1 - afterEach
    // 2 - afterAll
    // 1 - afterAll
    

    As you can see, beforeAll will be run before all of your test be executed. beforeEach will be run before each of you test. So beforeAll will be run before beforeEach