javascript - 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';
}
我想要的是按以下顺序执行的代码:
- 之前每个
- 获取城市
- 测试
- 获取城市2
- 测试
目前,测试之间的函数调用是异步执行的。如何以顺序方式执行它?
解决方案
也许你误会了beforeEach
。该beforeEach
块将在每个test()
. 因此,在您的情况下,按以下顺序执行测试:
- 之前每个
- 获取城市
- 测试1
- 获取城市2
- 测试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
推荐阅读
- javascript - LoginWithRedirect 不是函数
- javascript - 嵌套的“for”循环 - 打字稿角度
- class - 向 Woocommerce 缺货产品卡添加类 - 使用 Hestia 主题
- qt - 匹配 QGridLayout 中 Column 中最大小部件的宽度
- c - snprintf 在缓冲区溢出方面是否安全?
- python - 如何创建缺少年份的新行并用当前行填充它们
- mongodb - 如何使用 Mongodb 聚合框架填充数据?
- python - 使用 Docker 时 Socket IO 响应慢
- android - Data on Firestore console differs from the retrieved when consulting the database
- reactjs - create-react-app 未创建某些文件夹