admin管理员组

文章数量:1022964

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?

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?

Share Improve this question edited Feb 12, 2013 at 21:18 delixfe asked Aug 29, 2012 at 11:05 delixfedelixfe 2,4911 gold badge23 silver badges35 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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');

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?

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?

Share Improve this question edited Feb 12, 2013 at 21:18 delixfe asked Aug 29, 2012 at 11:05 delixfedelixfe 2,4911 gold badge23 silver badges35 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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');

本文标签: javascriptJasmine test a setTimeout function throws an errorStack Overflow