0

I tried to load multiple external js using javascript. I had separate code for injection logic. When I load one js file means the test case working fine. But when I try to load multiple js file the test case FAILED.

Main.js

var externalJs = "abcd.js";
function loadJs() {
  window.$script(externalJs);
}
function init(domElement) {
  loadJs();
}

module.exports = {
  init: init
};

Test.js

/* global assert, sinon*/
describe('Test', function () {
  var factory = require('main.js');
  it('oad the correct js library', function(){
    window.$script = sinon.spy();
    factory.init();
    sinon.assert.calledOnce(window.$script);

  });
});

The above code working fine. But when i try to load multiple external file the test case failed.

Main.js

var externalJs = [ "abcd.js", "xyz.js"];

function loadJs() {
  window.$script(externalJs[0], function(){
    window.$script(externalJs[1], function(){
    });
  });
}

function init(domElement) {
  loadJs();
}

module.exports = {
  init: init
};

Test.js

/* global assert, sinon*/

describe('Test', function () {
  var factory = require('main.js');
  it('oad the correct js library', function(){
    window.$script = sinon.spy();
    factory.init();
    sinon.assert.calledTwice(window.$script);
  });
});

Error Details:

expected $script to be called twice but was called once

Have any idea to fix this issue.

RSKMR
  • 1,812
  • 5
  • 32
  • 73
  • If there are actual network requests to get the scripts, you need to add a callback done() to your it-function to let your test wait for the scripts to load. Then when scripts are loaded, call done in the test – William Nov 06 '17 at 10:30

1 Answers1

0

The problem is that the first call to window.$script does not call the function callback that is provided as a parameter (in this case another call to window.$script).

Instead of using a sinon spy, try using a stub. With a stub, you can tell sinon to automatically call any function parameters that it receives.

window.$script = sinon.stub();

// configure the stub to automatically call any callbacks supplied
window.$script.yields();
Alex
  • 5,364
  • 9
  • 54
  • 69