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

Jest simple async await with timer not working

我正在尝试使用 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() 但这并没有解决问题。

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

尝试以下操作:

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');
});