Reputation: 803
I am trying to execute test case in a loop inside a forEach block, but variable which i am iterating always throws undefined. In beforeAll block i am using await to get a data from database and I am assigning array of objects to a variable so that i can iterate the array and execute the test for each object. but when i try to do that it always throws TypeError: Cannot read property 'forEach' of undefined, can anyone say what i am doing wrong here?
sample.test.ts
describe('Test suite ', () => {
let d: any;
beforeAll(async () => {
connectToDatabase();
d = await r.retriveDataFromDb1();
}, 200000);
describe('Test suite 1', () => {
d.forEach(function(v: any) {
it('test case', async () => {
console.log(v);
}, 20000);
});
});
});
Upvotes: 0
Views: 4114
Reputation: 222760
Jest tests may run asynchronously but they are defined synchronously. beforeAll
executes only when tests are started, test are supposed to be known at this time.
It can be either a single test that creates assertions dynamically:
let d: any;
beforeAll(async () => {
connectToDatabase();
d = await r.retriveDataFromDb1();
}, 200000);
describe('Test suite 1', () => {
it('test case', () => {
d.forEach((v: any) => {
expect(some).toBe(valueThatDependsOnV);
});
}, 20000);
});
Or asynchronous setup should take place in global setup where it's allowed:
// setup.js
module.exports = async () => {
connectToDatabase();
global.__d__ = await r.retriveDataFromDb1();
};
// teardown.js
module.exports = async function () {
// disconnect from database
};
__d__
will become available in all tests:
describe('Test suite 1', () => {
__d__.forEach((v: any) => {
it('test case', async () => {
...
}, 20000);
});
});
Upvotes: 2