Mochajs external script onload test

1.5k views Asked by At

I am trying to create a mochajs test to detect the script.onload event has been executed or the script.onerror. I have setup tests to detect the script exists in the DOM but am not sure how to check the actual loading.

 describe("Load external ABC Library", function() {

  var h = document.getElementsByTagName('head')[0];
  var s = document.createElement('script');
  s.src="http://host.com/script.js";
  s.id="abc";
  s.async=false;
  h.appendChild(s);

  var l = document.getElementById('abc');
  it.skip("is in the DOM", function () {
    expect(l).to.not.equal(null);
    console.log('is in the DOM was skipped');
  });

  it("is a child of the head", function () {
    expect(l.parentElement).to.equal(document.head);
  });

});
1

There are 1 answers

0
jrh On

One way to do this uses a virtual DOM via mocha-jsdom.

Example in CoffeeScript using mocha, chai, sinon, and sinon-chai:

addDynamicScript.coffee:

module.exports = (scriptName, callback) ->
  script = document.createElement 'script'
  script.type = 'text/javascript'
  script.async = true
  script.src = 'http://somewhere.com/async.js'
  script.onload = callback

  document.getElementsByTagName('body')[0].appendChild(script)

addDynamicScript.spec.coffee:

useDOM = require 'mocha-jsdom'
subject = require './addDynamicScript'

describe 'addDynamicScript', ->
  useDOM()

  beforeEach ->
    @getScript = -> document.getElementsByTagName('script')[0]

  # Reset jsdom between tests.
  afterEach ->
    document.getElementsByTagName('body')[0].removeChild(@getScript())

  it 'adds async script to the end of the body', ->
    subject()('something.js')
    body = document.getElementsByTagName('body')[0]
    expect(body.childNodes).to.have.length 1
    expect(body.childNodes[0]).to.eql @getScript()

  it 'runs given callback when script loads', ->    
    callback = spy()
    subject('something.js', callback)
    expect(callback).not.to.have.been.called

    script = @getScript()
    script.onload()
    expect(callback).to.have.been.called