简体   繁体   中英

Jest not executing test case inside forEach function

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM