I want to dynamically run multiple tests in Jest inside a for-loop but I am not sure where to place the asynchronous code that my test environment requires.
One option that works is to place all asynchronous code inside a test function and execute an assert statement for each iteration of the for-loop.
describe('Database Testing', () => {
test(`Testing ${items}`, async () => {
const items = await getItems(); //<-- asynchronous code
for (const item of items) {
expect('hi').toEqual('hi');
}
});
});
However, if the test fails, I will not be able to pinpoint which loop the assert statement failed in. Instead, I would like a structure similar to below where I dynamically run a test for each iteration of the for-loop.
describe('Database Testing', () => {
const items = await getItems(); //<-- asynchronous code
for (const item of items) {
test(`Testing ${item}`, async () => {
expect('hi').toEqual('hi');
});
};
});
I am unable to run the asynchronous code due to the synchronous nature of the describe function. Yet, if I use the async keyword in the describe function, I get the error 'Returning a Promise from "describe" is not supported'.
Where should I run the asynchronous code?
beforeAll
can be async. You can also have it
functions within describe
that are async.
Here is the jest documentation on testing async: 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
})
})
Just make sure that your expect.assertions
matches the appropriate number of assertions
.
will something like this work:
describe('Database Testing', () => {
getItems().then(items -> {
for (const item of items) {
expect('hi').toEqual('hi');
};
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.