[英]How to mock-up the .load function in Qunit?
我有一个要测试的JavaScript函数,包含.load。 该函数如下所示:
function getPane(divId) {
$("#" + divId).load(
"Pane.html",
function () {
//do some work here
});
});
}
我想使用Qunit进行测试,但不确定如何模拟这种行为。
我也不知道如何模拟同时具有.load和.get的函数-
function getPane(divId) {
$("#" + divId).load("Pane.html", function () {
$.get("/Config/Pane", function (data) {
//do work here
}
});
});
}
我只使用QUnit,没有使用Mockjax或Sinon.js或其他任何东西(我知道,我知道我应该)。 任何帮助,将不胜感激。 谢谢。
由于OP建议他们可以与Mockjax一起使用,所以我认为我会添加该解决方案。 请注意,我在安装方法中添加了模拟,然后将其拆解。 这允许每个测试都是幂等的。 另外,您的getPane()
函数需要回调,因此您可以在测试中添加断言。
function getPane(divId, cb) {
$("#" + divId).load("Pane.html", function () {
$.get("/Config/Pane", function (data) {
// do work here
cb(); // callback executed for any additional actions (like tests)
// you may want to add some error handling with callback as well
});
});
}
然后在qunit测试文件的#qunit-fixture
中,添加div以将内容放入:
<html>
...
<body>
<div id="qunit"></div>
<div id="qunit-fixture">
<div id="foobar"></div> <!-- our test element -->
</div>
...
</body>
</html>
现在编写模拟和测试:
QUnit.module("some tests", {
setup: function() {
$.mockjax({
url: "Pane.html",
responseText: "<div>Some HTML content</div>"
});
},
teardown: function() {
$.mockjax.clear(); // new in 1.6
}
});
QUnit.asyncTest("test it out", function(assert) {
getPane("foobar", function() {
assert.equal($("#foobar div").length, 0, "A new div was added to the page!");
QUnit.start();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.