murphyslaw
murphyslaw

Reputation: 636

How to test a JavaScript Image onerror callback in Jasmine?

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.

Upvotes: 1

Views: 1590

Answers (1)

Nick Rassadin
Nick Rassadin

Reputation: 900

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

Upvotes: 4

Related Questions