【发布时间】:2012-08-28 18:55:33
【问题描述】:
我正在尝试使用 QUnit 和 Mockjax 测试一些 jQuery ajax 代码,并让它为不同的测试返回不同的 JSON,like this:
$(document).ready(function() {
function functionToTest() {
return $.getJSON('/echo/json/', {
json: JSON.stringify({
"won't": "run"
})
});
}
module("first");
test("first test", function() {
stop();
$.mockjax({
url: '/echo/json/',
responseText: JSON.stringify({
hello: 'HEYO!'
})
});
functionToTest().done(function(json) {
ok(true, json.hello);
start();
});
});
test("second test", function() {
stop();
$.mockjax({
url: '/echo/json/',
responseText: JSON.stringify({
hello: 'HELL NO!'
})
});
functionToTest().done(function(json) {
ok(true, json.hello);
start();
});
});
});
不幸的是,它每次调用都返回相同的响应,并且无法保证顺序,所以想知道如何设置它以便与实际请求耦合并出现with this:
$.mockjax({
url: '/echo/json/',
response: function(settings) {
if (JSON.parse(settings.data.json).order === 1) {
this.responseText = JSON.stringify({
hello: 'HEYO!'
});
} else {
this.responseText = JSON.stringify({
hello: 'HELL NO!'
});
}
}
});
这依赖于发送到服务器的参数,但是没有参数的请求呢,我仍然需要测试不同的响应?有没有办法使用 QUnit 的 setup/teardown 来做到这一点?
【问题讨论】:
标签: jquery ajax asynchronous qunit mockjax