简体   繁体   English

处理Jasmine测试中的javascript错误

[英]Dealing with javascript errors in Jasmine tests

I'm developing a javascript application which listens to window.onerror() and reports to an endpoint me and my team are building. 我正在开发一个JavaScript应用程序,该应用程序侦听window.onerror()并向我和我的团队正在构建的端点报告。 I'm this using grunt-contrib-jasmine for the unit test side of things and am running into issues since my test cases expect errors to be thrown. 我正在使用grunt-contrib-jasmine进行单元测试,由于我的测试用例预计会引发错误,因此我遇到了问题。

When running test cases with phantom, this clutters up my output unnecessarily: http://cl.ly/image/1n3k3z2g2V2l 使用幻像运行测试用例时,这会不必要地使我的输出混乱: http : //cl.ly/image/1n3k3z2g2V2l

In the instance of the reference error, my test looks like this: 在参考错误的情况下,我的测试如下所示:

it("should report reference errors", function() {
    spyOn(window.fred, 'sendRequest').andCallFake(function(details) {
        expect(details.type).toEqual('js-error');
        expect(details.message).toBeNonEmptyString();
    });
    runs(function() {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.innerHTML = 'reference_error;';
        document.body.appendChild(script);
    });

    waits(2000);

    runs(function() {
        expect(window.fred.sendRequest).toHaveBeenCalled();
    });
});

I want to be able to handle the ReferenceError which gets thrown at some point in the code. 我希望能够处理在代码中某些时候引发的ReferenceError。 As best I can see, this happens indirectly at document.body.appendChild(script); 最好的是,这间接发生在document.body.appendChild(script); . Jasmine's expect(fn).toThrow(e) looks like it would do the job if I used it here however the test still fails. 如果我在这里使用Jasmine的expect(fn).toThrow(e)看起来可以完成任务,但是测试仍然失败。 I've also tried surround it with a try { ... } catch (err) { ... } but to no avail. 我也尝试过用try { ... } catch (err) { ... }包围它,但无济于事。

My question, does anyone have any suggestions on how to deal with this? 我的问题是,有人对如何处理有任何建议吗?

Normally jasmine will try to catch any exceptions that are thrown by your specs and have those mark the spec as failed. 通常,茉莉花会尝试捕获您的规范引发的任何异常,并将这些异常标记为失败。 However, because this exception is being thrown by the browser when it tries to parse your script tag, jasmine isn't in the call stack. 但是,由于浏览器在尝试解析脚本标记时会抛出此异常,因此茉莉花不在调用堆栈中。 This is why toThrow doesn't work. 这就是为什么toThrow不起作用。

Also, as long as your onerror method returns true the browser should not do it's default error action , in this case log to the console. 另外,只要您的onerror方法返回true ,浏览器就不应执行其默认错误操作 ,在这种情况下,请登录到控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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