4

I would like to test the error handling of a method, which schedules work with setTimeout. The error will be thrown in the scheduled part, i.e.:

function sutWithSetTimeout() {
    setTimeout(function () { throw new Error("pang"); }, 1);
}

How do I test that an error is thrown and that it has the correct message?

delixfe
  • 2,433
  • 1
  • 18
  • 32

1 Answers1

8

You need to catch the function in the setTimeout and call them using expect(function(){fn();}).toThrow(e);. So you can spy on setTimeout to get the function:

spyOn(window, 'setTimeout');
sutWithSetTimeout();
var fn = window.setTimeout.mostRecentCall.args[0];
expect(fn).toThrow('pang');
John Kurlak
  • 6,331
  • 7
  • 41
  • 58
Andreas Köberle
  • 98,250
  • 56
  • 262
  • 287