Mochajs外部脚本onload测试

时间:2015-06-18 18:15:31

标签: mocha mocha-phantomjs

我正在尝试创建一个mochajs测试来检测script.onload事件是否已执行或者是script.onerror。我已经设置了测试来检测DOM中存在的脚本,但我不确定如何检查实际的加载。

 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 个答案:

答案 0 :(得分:1)

一种方法是通过mocha-jsdom使用虚拟DOM。

使用mochachaisinonsinon-chai的CoffeeScript中的示例:

<强> 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