QUnitとMockjaxを使用してjQueryajaxコードをテストし、次のように、テストごとに異なるJSONを返すようにしています。
$(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();
});
});
});
残念ながら、呼び出しごとに同じ応答が返され、順序は保証されないため、実際の要求に結合してこれを思い付くように設定するにはどうすればよいか疑問に思いました。
$.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のセットアップ/ティアダウンを使用してこれを行う方法はありますか?