Jest not executing test case inside forEach function

落爺英雄遲暮 提交于 2021-01-29 05:27:30

问题


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);
    });
  });
});

回答1:


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);
    });
  });


来源:https://stackoverflow.com/questions/61319904/jest-not-executing-test-case-inside-foreach-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!