lundi 16 novembre 2020

How to loop through jest tests synchronously

I am currently looping through a Jest test suite multiple times in my code and need to access a value from the afterAll block after each test iteration.

Once all iterations and tests are finished, I need to do some calculations for these values from the afterAll block.

The problem is the tests being run in the loop are asynchronous and by the time I get to my calculate function, there's no values yet.

So My current effort is to return a Promise for each iteration and resolving the value I need, however this loop stops just after 1 iteration. It will complete 1 test successfully, and the 2nd test will reach the describe block, but will never reach the beforeAll block or anything after.

How can I wait for all tests in the loop to finish, before moving on to my calculations function?

Here is part of my code:

function startTestSuite(testDetails, config) {
  return new Promise((resolve, reject) => {

    describe('Test Google page', () => {
      jest.setTimeout(JEST_TIMEOUT);

      beforeAll(async () => {
        timerA = performance.now();
        browser = await new BrowserDriver(testDetails);
        await browser.build(config);
      });

      afterAll(async () => {
        await browser.quit();
        timerB = performance.now();
        const totalTime = Math.ceil(timerB - timerA);
        resolve(totalTime);
      });

      test('should navigate to Google and get title', async () => {
        await browser.navigateTo(TEST_URL, testDetails);
        const title = await browser.getTitle(testDetails);
        expect(title).toEqual('Google');
      });
    });
  });
}

async function startTests() {
  const testDetails = {
    testCount: 0,
    tunnelId,
    tunnelName,
    buildId
  };

  for (let i = 1; i < NUMBER_OF_TESTS; i++) {
    testDetails.testCount = i;
    const config = configSauceLabs(testDetails);
    const totalTime = await startTestSuite(testDetails, config);
    performanceArr.push(totalTime);
  }

  // Run calculations function
}

startTests();

Aucun commentaire:

Enregistrer un commentaire