玩笑简单异步等待计时器不起作用

时间:2019-06-24 10:55:40

标签: timer async-await jestjs settimeout

我正在尝试使用setTimeout进行简单的异步/等待测试,但是运行它时却什么也没发生:

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(),但这并不能解决问题。

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

1 个答案:

答案 0 :(得分: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');
});