我有一个要测试的 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();
});
});
关于javascript - 如何在Qunit中模拟.load函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26353162/