【问题标题】:Jest - Sequential Execution of a describe blockJest - 描述块的顺序执行
【发布时间】:2019-06-21 07:52:16
【问题描述】:

我正在使用 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. getCity2
  5. 测试

目前,测试之间的函数调用是异步执行的。怎么可能按顺序执行呢?

【问题讨论】:

标签: javascript jestjs


【解决方案1】:

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

  1. 每个之前
  2. 获取城市
  3. 测试1
  4. getCity2
  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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-01
    • 1970-01-01
    • 2012-11-23
    • 1970-01-01
    • 2016-06-07
    • 2020-06-02
    • 1970-01-01
    • 2019-05-25
    相关资源
    最近更新 更多