Multiple responses from identical calls in asynch QUnit + Mockjax tests
Posted
by
NickL
on Stack Overflow
See other posts from Stack Overflow
or by NickL
Published on 2012-08-28T18:55:33Z
Indexed on
2012/10/24
17:01 UTC
Read the original article
Hit count: 332
I'm trying to test some jQuery ajax code using QUnit and Mockjax and have it return different JSON for different tests, 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();
});
});
});
Unfortunately it returns the same response for each call, and order can't be guaranteed, so was wondering how I could set it up so that it was coupled to the actual request and came up 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!'
});
}
}
});
This relies on parameters being sent to the server, but what about requests without parameters, where I still need to test different responses? Is there a way to use QUnit's setup/teardown to do this?
© Stack Overflow or respective owner