2 回答

TA贡献1869条经验 获得超4个赞
如果不等待,就不可能从awaitFirstStreamForPage(page)with 中捕捉到拒绝。try..catch
拒绝应该被捕获但是在调用之后advanceTimersByTime并且可能在 之后flushPromises。
有可能:
const promise = awaitFirstStreamForPage(page);
promise.catch(() => { /* suppress UnhandledPromiseRejectionWarning */ });
jest.advanceTimersByTime(10000)
await flushPromises();
await expect(promise).rejects.toThrow('no stream found for 10000ms');

TA贡献1777条经验 获得超3个赞
问题似乎不是假计时器的使用:您预期的错误是被抛出的错误。但是,在 Jest 中测试抛出错误的函数时,您应该将抛出错误的代码包装在一个函数中,如下所示:
expect(()=> {/* code that will throw error */}).toThrow()
更多细节在这里: https: //jestjs.io/docs/en/expect#tothrowerror
编辑:对于异步函数,你应该使用rejects
before toThrow
;看这个例子:Can you write async tests that expect toThrow?
添加回答
举报