Jasmine spy element onload

1.7k Views Asked by At

I'm creating dynamically some scripts like this:

  var js1 = document.createElement('script');
  js1.type = 'text/javascript';
  js1.src = '/js-1.js';
  docmuent.body.appendChild(js1);
  js1.onload = function() {
     var js2 = document.createElement('script');
     js2.type = 'text/javascript';
     js2.src = '/js-2.js';
     document.body.appendChild(js2);
  };

Here's my spec:

  it('Tests inject script', function() {
    expect($("script[src*='/js-1.js']").length).toBeGreaterThan(0);
    expect($("script[src*='/js-2.js']").length).toBeGreaterThan(0);
  });

The test on js-2 always fails. How can i spy js-1 onload event ?

2

There are 2 best solutions below

1
On

I think the problem may be in your ordering. You should create the script tag, add it to the body, set the onload, and then set the src.

var js1 = document.createElement('script');
js1.type = 'text/javascript';
docmuent.body.appendChild(js1);
js1.onload = function() {
   var js2 = document.createElement('script');
   js2.type = 'text/javascript';
   document.body.appendChild(js2);
   js2.src = '/js-2.js';
};
js1.src = '/js-1.js';
0
On

You shouldn't add the tag creation code inside the onload event. If I'm not wrong IE will only start downloading the file as soon as the script tag is added to the DOM.

My suggestion is to move everything you have in the onload event outside and maybe have a handler function inside the onload event to know for sure when the file has finished loading. This way your only problem will be testing the call of the function inside the onload event. You can do that by mocking document.createElement('script'); and return a fake object that you can use like "fakeObject.onload()" and spy if your inner helper function is called.