How to test a JavaScript Image onerror callback in Jasmine?

て烟熏妆下的殇ゞ 提交于 2019-12-12 01:37:39

问题


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.

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;
  };
}

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");

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.


回答1:


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

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

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");
  });
});

You can find more on testing async code with Jasmine in this article



来源:https://stackoverflow.com/questions/36508714/how-to-test-a-javascript-image-onerror-callback-in-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!