我知道你想做什么…但是有一个
tool to mock out Ajax requests
就为了这个目的!(我是它的维护者,但仍然…)
基本上,在你的测试(或
beforeEach
hook
)您可以根据实际的Ajax调用创建一个模拟,然后进行代码测试。
首先,我将在源代码函数中添加回调,这样我们就可以知道在测试中何时完成Ajax调用:
function getUpdateForm(doneFunction) {
$.ajax({
url: 'test_response.html',
type: 'GET',
dataType: 'json',
success: function(data) {
$("#Form_div").html(data);
},
complete: doneFunction // <-- this is new!
});
};
现在用一个模拟设置测试,并执行断言…
QUnit.test('getUpdateForm ajax request', function(assert) {
let done = assert.async(); // set up an async test
$.mockjax({
url: "test_response.html",
responseText: "<h1>Test Page</h1>"
});
getUpdateForm(function() { // this is our callback function
// now do your assertions on the content in the form div...
assert.equal($("#Form_div h1").text(), 'Test Page', 'Received correct title in html response');
done(); // then tell QUnit you are done testing.
});
});
不要忘记包含mockjax JS文件
除了
Qunit JS文件!