首页 > 解决方案 > Jest - 描述块的顺序执行

问题描述

我正在使用 jest 执行 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. 之前每个
  2. 获取城市
  3. 测试
  4. 获取城市2
  5. 测试

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

标签: javascriptjestjs

解决方案


也许你误会了beforeEach。该beforeEach块将在每个test(). 因此,在您的情况下,按以下顺序执行测试:

  1. 之前每个
  2. 获取城市
  3. 测试1
  4. 获取城市2
  5. 测试2

您可以改为使用,然后在适当的测试块中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


推荐阅读