gpt4 book ai didi

javascript - 在 Document.ready 上调用函数的测试用例

转载 作者:行者123 更新时间:2023-11-28 05:33:25 25 4
gpt4 key购买 nike

我的JS代码如下:

if (typeof IPL === "undefined") {
IPL = {};
}

/// <summary>Declare Namespace IPL.Register</summary>
if (typeof IPL.Register === "undefined") {
IPL.Register = {};
}

$(document).ready(function () {
IPL.Register.Print.initialize();
});

/// <summary>Declare Namespace IPL.Register.Print</summary>
IPL.Register.Print =
{
/// <summary>Function to call on initialize page.</summary>
initialize: function () {
window.onload = function () {
window.print();
};
}
};

当我运行下面提到的测试用例(Qunit.js 和毯子.js)时,不会调用 Document.ready 函数,并且代码覆盖率不会覆盖该行。下面的测试用例工作正常,但它只包括最后几行代码和窗口加载时的初始化函数。

test("initialize test", 1, function () {
var result = IPL.Register.Print.initialize();
equal(undefined, result, "passed");
});

有人请协助如何编写测试用例以在文档加载时执行函数?

最佳答案

做到这一点的最佳方法是根本不测试加载事件。只需将事件处理程序放入命名函数中,然后测试该函数的行为即可。

/// <summary>Declare Namespace IPL.Register.Print</summary>
IPL.Register.Print = {
/// <summary>Function to call on initialize page.</summary>
initialize: function() {
window.onload = function() {
window.print();
};
},
print: function() {
window.print();
}
};

test("initialize test", 1, function() {
var result = IPL.Register.Print.print();
equal(undefined, result, "passed");
});

http://jsfiddle.net/Tintin37/vpqjsr8L/

load事件只是运行你的函数,你想通过测试load事件具体实现什么目的?

关于javascript - 在 Document.ready 上调用函数的测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39530140/

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