简体   繁体   中英

Jest how to test error thrown in setTimeout

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?

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

You can test it like this:

it('should throw an error', (done) => {
  myFunc();

  setTimeout(function() {
    expect(myFunc).toThrowError('err within setTimeout');
    done();
  }, 1000);
})

Check this article

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM