gpt4 book ai didi

mocha.js - Mochajs外部脚本onload测试

转载 作者:行者123 更新时间:2023-12-02 03:24:56 24 4
gpt4 key购买 nike

我正在尝试创建一个 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);
});

});

最佳答案

一种方法是通过 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

关于mocha.js - Mochajs外部脚本onload测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30922791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com