Reputation: 21
My code looks like this:
const myFunc =() =>{
setTimeout(()=>throw new Error('err within setTimeout'),500);
}
How do I test in the Jest framework that the error is thrown?
Upvotes: 2
Views: 758
Reputation: 23753
The only way I see is to mock setTimeout
itself to make it run synchronously. jest.useFakeTimers()
+ jest.runAllTimers()
can do that for you:
jest.useFakeTimers();
it("throws", () => {
expect.assertions(1); // don't miss that to ensure exception has been thrown!
myFunc();
try {
jest.runAllTimers();
} catch(e) {
expect(e.message).toEqual('err within setTimeout');
}
});
Upvotes: 1