4

我对 javascript 相当陌生,并且正在尝试使用 jasmine 对一些错误处理代码进行单元测试。

特别是,我正在尝试编写一些测试来验证替换 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 在 Firefox 中未触发
在 Selenium 中捕获 JavaScript 错误
window.onerror 不起作用
如何在 Internet Explorer 中触发 script.onerror?

根据其中一些人的说法,我认为在调试器中运行规范测试会强制触发 onerror,但不会触发骰子。有人知道更好的方法吗?

4

2 回答 2

3

我最近基于类似于 Jasmine的Buster.JS开发了带有单元测试的小型JavaScript 错误处理程序。

执行 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()

于 2013-10-22T17:23:41.397 回答
1

没有茉莉花的知识。

所有单元测试都在 try/catch 块内运行,因此如果一个测试终止,下一个测试可以运行(至少对于 QUnit 来说是真的)。而且由于 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 以获得正确的文件和行号。

在单元测试中调用这样的函数时,最好简单地测试您的函数是否已设置以及在使用所有伪造参数调用时它是否正常运行。

于 2013-10-22T13:16:58.757 回答