我想在 for 循环中以 Jest 动态运行多个测试,但我不确定将测试环境所需的异步代码放在哪里。
一个有效的选项是将所有异步代码放在测试函数中,并为 for 循环的每次迭代执行断言语句。
describe('Database Testing', () => {
test(`Testing ${items}`, async () => {
const items = await getItems(); //<-- asynchronous code
for (const item of items) {
expect('hi').toEqual('hi');
}
});
});
但是,如果测试失败,我将无法确定断言语句在哪个循环中失败。相反,我想要一个类似于下面的结构,其中我为 for 循环的每次迭代动态运行测试。
describe('Database Testing', () => {
const items = await getItems(); //<-- asynchronous code
for (const item of items) {
test(`Testing ${item}`, async () => {
expect('hi').toEqual('hi');
});
};
});
由于描述函数的同步性质,我无法运行异步代码。但是,如果我在描述函数中使用 async 关键字,则会收到错误"不支持从"描述"返回承诺"。
我应该在哪里运行异步代码?
beforeAll
可以是异步的。您还可以在describe
中具有异步it
函数。
以下是有关测试异步的开玩笑文档:https://jestjs.io/docs/en/tutorial-async
beforeAll(async () => {
// do async things
})
describe('whatever', () => {
it('will do something async', async () => {
expect.assertions(1);
// do something async
//... expect something
})
})
只需确保您的expect.assertions
与适当的assertions
数匹配即可。
这样的事情会起作用:
describe('Database Testing', () => {
getItems().then(items -> {
for (const item of items) {
expect('hi').toEqual('hi');
};
});
});