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?

1
  • 1
    Duplicated of Question Commented Jan 28, 2019 at 10:29

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.