开玩笑不在forEach函数内执行测试用例 [英] Jest not executing test case inside forEach function
问题描述
我正在尝试在forEach块内的循环中执行测试用例,但是我要迭代的变量始终会抛出未定义的情况.在beforeAll块中,我正在使用await从数据库中获取数据,并且将对象数组分配给变量,以便可以迭代该数组并对每个对象执行测试.但是当我尝试这样做时,它总是抛出 TypeError:无法读取未定义的属性'forEach',有人可以在这里说我在做什么吗?
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
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);
});
});
});
推荐答案
玩笑测试可能异步运行,但它们是同步定义的. beforeAll
仅在开始测试时执行,应该在这个时候知道测试.
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__
将在所有测试中可用:
__d__
will become available in all tests:
describe('Test suite 1', () => {
__d__.forEach((v: any) => {
it('test case', async () => {
...
}, 20000);
});
});
这篇关于开玩笑不在forEach函数内执行测试用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!