mocha - Mochajs external script onload test -
i trying create mochajs test detect script.onload event has been executed or script.onerror. have setup tests detect script exists in dom not sure how check 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 dom", function () { expect(l).to.not.equal(null); console.log('is in dom skipped'); }); it("is child of head", function () { expect(l.parentelement).to.equal(document.head); }); });
one way uses virtual dom via mocha-jsdom
.
example in coffeescript using mocha
, chai
, sinon
, , 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()) 'adds async script end of body', -> subject()('something.js') body = document.getelementsbytagname('body')[0] expect(body.childnodes).to.have.length 1 expect(body.childnodes[0]).to.eql @getscript() '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
Comments
Post a Comment