2012-05-04 69 views
3

我是相当新的JavaScript和我试图用茉莉来单元测试一些错误处理代码。单元测试window.onerror与茉莉

特别是,我试图编写一些测试来验证替代window.onerror()的我们的自定义代码(称为windowHandleError)被调用,并且正在做我们想要的。

我试图沿着线的东西:

 it("testing window.onerror", function() { 
     spyOn(globalerror, 'windowHandleError'); 
     globalerror.install(); 

     var someFunction = function() { 
      undefinedFunction(); 
     }; 
     expect(function() {someFunction();}).toThrow(); 
     expect(globalerror.windowHandleError).toHaveBeenCalled(); 
    }); 

但它不会触发onerror的。我看过一些相关的问题,但他们似乎询问特定的浏览器,或者如何/在哪里使用onerror,而不是如何测试它。
window.onerror not firing in Firefox
Capturing JavaScript error in Selenium
window.onerror does not work
How to trigger script.onerror in Internet Explorer?

基于一些什么那些说,我想在运行调试器的规范测试将强制使用onerror触发,但没有骰子。任何人都知道更好的方法呢?

回答

0

没有茉莉花知识。

所有的单元测试都在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获取正确的文件和行号。

在单元测试中调用像这样的函数时,最好简单地测试一下你的函数是否已设置,并且在使用所有伪造的参数调用时它会正常工作。

3

我最近开发的小型JavaScript error handler单元测试基于Buster.JS这是类似于茉莉花。

The test that exercises the 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的回调中一个现实生活中的错误,不会停止测试执行,将检查间谍被称为100毫秒后在另一个的setTimeout,然后调用done()这是您如何使用Buster.JS测试异步功能。 The same approach is available with Jasmine在异步测试中使用done()

+0

伟大的想法,我想不出如何获得错误处理程序称为只是测试我的代码诠释他的浏览器,setTimeout()做的伎俩。 –