Jasmine:测试一个setTimeout函数会抛出一个错误 [英] Jasmine: test a setTimeout function throws an error

查看:167
本文介绍了Jasmine:测试一个setTimeout函数会抛出一个错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试一个方法的错误处理,该方法使用setTimeout进行调度。错误将在计划部分中抛出,即:

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?

推荐答案

您需要捕获 setTimeout 中的函数并调用他们使用 expect(function(){fn();})。toThrow(e); 。所以你可以窥探 setTimeout 来获得这个函数:

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

这篇关于Jasmine:测试一个setTimeout函数会抛出一个错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆