0

I'm executing a describe() block using jest. between each test() I'd like to execute code in a synchronous manner, for example:

describe('matching cities to foods', () => {
  // Applies only to tests in this describe block
  beforeEach(() => {
    return initializeFoodDatabase();
  });
  
  const city = getCity();
  
  test('Vienna <3 sausage', () => {
    expect(isValidCityFoodPair(city, 'Wiener Schnitzel')).toBe(true);
  });
  
  let city2 = getCity2();

  test('San Juan <3 plantains', () => {
    expect(isValidCityFoodPair(city2, 'Mofongo')).toBe(true);
  });
});

function getCity(){
  return 'Vienna';
}

function getCity2(){
  return 'San Juan';
}

What I want is the code to be executed in the following sequence:

  1. beforeEach
  2. getCity
  3. test
  4. getCity2
  5. test

Currently, the function calls between tests are being executed asynchronously. How is it possible to execute it in a sequential manner?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Shizzle
  • 961
  • 3
  • 10
  • 27

1 Answers1

1

Maybe you misunderstood beforeEach. The beforeEach block will be called multiple times before each test(). So in your case, to execute tests in the following sequence:

  1. beforeEach
  2. getCity
  3. test1
  4. getCity2
  5. test2

You can use beforeAll instead then call getCity() and getCity2() in appropriate test block like this:

describe('matching cities to foods', () => {
  // Applies only to tests in this describe block
  beforeAll(() => {
    return initializeFoodDatabase();
  });

  test('Vienna <3 sausage', () => {
    const city = getCity();
    expect(isValidCityFoodPair(city, 'Wiener Schnitzel')).toBe(true);
  });


  test('San Juan <3 plantains', () => {
    const city2 = getCity2();
    expect(isValidCityFoodPair(city2, 'Mofongo')).toBe(true);
  });
});

Check the docs for more info: https://jestjs.io/docs/en/setup-teardown

Cuong Vu
  • 3,423
  • 14
  • 16