如何在Jasmine中测试JavaScript Image onerror回调? [英] How to test a JavaScript Image onerror callback in Jasmine?

查看:105
本文介绍了如何在Jasmine中测试JavaScript Image onerror回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以在URL中传递的url加载器,它将使用动态创建的JavaScript new Image()及其 src 要加载网址的属性。如果发生错误,我将其记录到控制台。

I'm having an url loader that I can pass in an URL and it will use a dynamically created JavaScript new Image() and its src property to load the url. In case an error happens, I'm logging it to the console.

简化的JavaScript代码将是:

The simplified JavaScript code would be:

var UrlLoader = function(url) {
  this.url = url;
  this.image = new Image();

  this.image.onerror = function() {
    console.log("image error");
  };

  this.load = function() {
    this.image.src = this.url;
  };
}

我现在的问题是,我如何测试我运行时执行console.log(图像错误)

My question now is, how I can test that console.log("image error") is executed, when I run

var urlLoader = new UrlLoader();
urlLoader.load("any.png");

我创建了一个 JSFiddle与测试套件设置,但规格失败,并希望找到一种方法来测试 UrlLoader

I created a JSFiddle with the test suite set up, but failing specs and would appreciate any help on figuring out a way to test the UrlLoader.

推荐答案

这是您用来检查是否调用了log方法的行

This is line you use to check if log method was called

expect(console.log).toHaveBeenCalledWith("image error");

这是正确的但问题是 onerror 处理程序此时尚未调用,因为错误事件不是立即触发/处理,而是后来异步触发

It's correct but problem that is onerror handler has not yet called by this time, because error event to be fired/handled not immediately but later asynchronically

您应该将测试用例更改为此

You should change your test case to this

describe("A suite", function() {

  beforeEach(function(done){
    spyOn(console, "log");

    var imageLoader = new ImageLoader("any.png");
    imageLoader.image.addEventListener("error", function() {
        done();
    });
    imageLoader.load(); 
  });

  it("contains spec with an expectation", function() {
    expect(console.log).toHaveBeenCalledWith("image error");
  });
});

您可以在这篇文章

这篇关于如何在Jasmine中测试JavaScript Image onerror回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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