How to run concurrent tests in Jest with multiple tests per request?

前端 未结 2 890
旧巷少年郎
旧巷少年郎 2021-01-20 21:53

I\'d like to run my Jest tests concurrently, but I\'m having issues with one scenario:

I\'m testing the results on an endpoint, and I want to test multiple things ab

2条回答
  •  被撕碎了的回忆
    2021-01-20 22:32

    Was having same issue when doing browser testing with Playwright where one test suite only requires one instance of browser. Had to wrap it with a Promise with setInterval. In your case it should be like below:

    let data;
    
    beforeAll(async () => {
        data = await getDataFromRequest();
    }
    test.concurrent('value1 should be truthy', async () => {
        await waitForData();
        expect(data.value1).toBeTruthy();
    }
    test.concurrent('value2 should be truthy', async () => {
        await waitForData();
        expect(data.value2).toBeTruthy();
    }
    
    /**
     * @param {number} interval -  the interval to check data availability
     * @param {number} timeout -  the overall timeout value
     * @return Promise of your data OR reject if timeout.
     */
    function waitForData(interval = 500, timeout = 5000){
      let acc = 0; // time accumulation
      return new Promise((resolve, reject) => {
        const i = setInterval(() => {
          acc += interval;
          if (data) {
            clearInterval(i);
            resolve(data);
          }
          if (acc > timeout) {
            clearInterval(i);
            reject();
          }
        }, interval);
      });
    }
    
    

    So you just need to assign the proper check interval and timeout which should be long enough for your data asycn call to come back.

提交回复
热议问题