【问题标题】:Jest simple async await with timer not working开玩笑的简单异步等待计时器不起作用
【发布时间】:2019-06-24 10:55:40
【问题描述】:

我正在尝试使用 setTimeout 进行简单的 async/await 测试,但运行时没有任何反应:

const testing = async () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('result');
        }, 500);
    });
}

jest.useFakeTimers()

it('tests async await', async () => {
    const r = await testing();
    expect(r).toBe('result');

    jest.runAllTimers();
});

我可以像在 Jasmine 中那样使用真正的 setTimeout,但在 Jest 中您似乎必须使用假的。所以我确实包含了jest.useFakeTimers()jest.runAllTimers(),但这并没有解决它。

测试卡住了,永远无法完成。知道可能是什么问题吗?

【问题讨论】:

    标签: timer async-await jestjs settimeout


    【解决方案1】:

    尝试以下操作:

    it('tests async await', async () => {
        jest.useFakeTimers();
        testing = async () => {
          return new Promise((resolve, reject) => {
            setTimeout(() => {
              resolve('result');
            }, 500);
          });
        };
        const asyncResult = testing();
        jest.runAllTimers();
        const r = await asyncResult;
        expect(r).toBe('result');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-11
      • 1970-01-01
      • 2023-02-09
      • 1970-01-01
      • 2020-01-27
      • 1970-01-01
      • 2019-06-30
      • 2016-11-11
      相关资源
      最近更新 更多