单元测试窗口.onerror with jasmine.
Unit testing window.onerror with jasmine
我对javascript相当陌生,正在尝试使用Jasmine来单元测试一些错误处理代码。
特别是,我正在尝试编写一些测试来验证我们的自定义代码(称为windowHandleError)替换window.onerror()是否被调用,并且正在执行我们想要的操作。
我已经尝试了类似以下内容的方法:
it("testing window.onerror", function() {
spyOn(globalerror, 'windowHandleError');
globalerror.install();
var someFunction = function() {
undefinedFunction();
};
expect(function() {someFunction();}).toThrow();
expect(globalerror.windowHandleError).toHaveBeenCalled();
});
但它不会触发错误。 我看过一些相关的问题,但它们似乎询问了特定的浏览器,或者如何/在哪里使用 onerror 而不是如何测试它。
window.onerror 在 Firefox
中未触发在Selenium
中捕获JavaScript错误窗口错误不起作用
如何在 Internet Explorer 中触发 script.onerror?
根据其中一些人所说的话,我认为在调试器中运行规范测试会强制触发onerror,但没有骰子。 有谁知道更好的方法吗?
我最近开发了基于 Buster 的小型 JavaScript 错误处理程序.JS它类似于 Jasmine。
执行 window.onerror 的测试如下所示:
"error within the system": function (done) {
setTimeout(function() {
// throw some real-life exception
not_defined.not_defined();
}, 10);
setTimeout(function() {
assert.isTrue($.post.called);
done();
}, 100);
}
它在 setTimeout 回调中抛出一个现实生活中的错误,该回调不会停止测试执行,并将检查在另一个 setTimeout 中 100 毫秒后是否调用了间谍,然后调用done()
这就是您使用 Buster.JS 测试异步功能的方式。Jasmine 可以通过在异步测试中使用 done()
来获得相同的方法。
不了解茉莉花。
所有单元测试都在 try/catch 块内运行,因此如果一个测试死亡,下一个测试可以运行(至少对于 QUnit 为 True)。由于 window.onerror 不会捕获已经在 try/catch 中捕获的异常,因此在单元测试中测试它时它不会运行。
尝试根据异常手动调用 onerror 函数。
try {
//Code that should fail here.
someUndefinedFunction();
} catch (e) {
window.onerror.call(window, e.toString(), document.location.toString(), 2);
}
expect(globalerror.windowHandleError).toHaveBeenCalled();
这远非完美,因为 document.location 与 url 参数不同,您需要手动设置行号。更好的方法是解析 e.stack 以获得正确的文件和行号。
在单元测试中像这样调用函数时,最好简单地测试您的函数是否已设置,并且在使用所有伪造的参数调用时它是否正常运行。
- Fighting with FRP
- issue with FB.Event.subscribe
- 使用jasmine模拟对服务器的调用
- geolocation-marker.js conflict with markerclusterer.js
- Angular 2.0 with JavaScript or TypeScript?
- 为什么不推荐使用“with”?是否有更好或其他方法可以“下降”到对象的命名空间
- WebComponentsJS with IE10
- 为什么jasmine期望不验证是否抛出了错误
- 模拟chrome.storage.local函数使用Jasmine
- 指令的模板必须只有一个根元素:With restrict E&替换true
- Jasmine Testing with Angular Promise 无法使用 TypeScript 解析
- JavaScript: toLocaleString() testing with jasmine
- 单元测试窗口.onerror with jasmine.
- Jasmine和Karma with Jasmine给出了不同的结果
- Testing Moment.js with Jasmine
- AngularJS控制器的Unittest with Jasmine and Karma "无法读取属性
- Testing jQuery Hover with Jasmine
- Running jasmine specs headlessly with phantomjs
- Spying on console.error() with Jasmine
- Testing JavaScript readline with Jasmine