Mochajs external script load test

I am trying to create a mochajs test to detect script.onload or script.onerror event. I have setup tests to detect a script exists in the DOM, but I'm not sure how to check the actual download.

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

});

      

+3


source to share


1 answer


One way to do this is using the virtual DOM via mocha-jsdom

.

EXAMPLE CoffeeScript in 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

      

+1


source







All Articles