使用笑话来测试调用递归函数的超时

问题描述

我要测试以下代码

const poll = (maxTries,interval,channel,stopTime) => {
    let reached = 1;
    const someinformation = someGetter();
    const fetchData = async (resolve,reject) => {
        const data = await networkClass.someApiCall();
        if (data.stopTime === 1581516005) {
            console.log("cond true");
            someinformation.Meta1 = transFormer(someinformation);
            someinformation.Meta2 = transFormer(someinformation);
            someinformation.Meta3 = {
                ...someinformation.Meta1,data,};

            resolve(someinformation);
        } else if (reached < maxTries) {
            reached += 1;
            console.log("do it again");
            setTimeout(fetchData,resolve,reject);
        } else {
            reject(new Error('max retries reached'));
        }
    };

    return new Promise(fetchData);
};

const checkForUpdates = () => {
    setTimeout(() => {
        poll(/* max retries */ 10,/* polling interval */ 1000,stopTime)
            .then((res) => {
                setData(res);
                console.log({ res: res.Meta3.data });
            })
            .catch((e) => console.log({ e }));
    },20000);
};

测试如下:

 it(`should do stuff`,() => {
      jest.spyOn(networkClass,'someApiCall')
          .mockResolvedValueOnce({ stopTime })
          .mockResolvedValueOnce({ stopTime })
          .mockResolvedValueOnce({ stopTime: 1581516005 });

      checkForUpdates();
      jest.advanceTimersByTime(40000);

      expect(setDataMock).toHaveBeenCalled();
});

该console.log(console.log(“再次做一次”);)仅打印一次,就好像测试无法在setTimeout中调用setTimeout一样。您有什么想法可能有帮助吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)