开玩笑-describe块的顺序执行

时间:2019-01-28 10:20:40

标签: javascript jestjs

我正在使用笑话来执行describe()块。 在每个test()之间,我想以同步方式执行代码,例如:

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';
}

我想要的是按以下顺序执行的代码:

  1. beforeEach
  2. getCity
  3. 测试
  4. getCity2
  5. 测试

当前,测试之间的函数调用是异步执行的。如何以顺序方式执行它?

1 个答案:

答案 0 :(得分:0)

也许您误解了beforeEachbeforeEach块将在每个test()之前被多次调用。因此,根据您的情况,请按以下顺序执行测试:

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

您可以使用beforeAll代替,然后在适当的测试块中调用getCity()getCity2(),如下所示:

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);
  });
});

检查文档以获取更多信息:https://jestjs.io/docs/en/setup-teardown