I have a JavaScript function that does a Post to a remote API that I am looking at writing a unit test for. The method I want to test is this:
var functionToTest = function(callback, fail) {
$.ajax({
url: "/myapi/",
type: "POST",
data: { one: 'one', two: 'two' },
accept: "application/json",
contentType: "application/json"
}).done(function(x) {
log = generateLogMessage('Success');
callback(log);
}).fail(function(x, s, e) {
log = generateLogMessage('Fail');
fail(log);
});
}
I have a unit test (in QUnit leveraging Sinon.js) that tests that the callback is called correctly when the request succeeds:
QUnit.test('Test that the thing works', function () {
var server = this.sandbox.useFakeServer();
server.respondWith(
'POST',
'/myapi/',
[
200,
{'Content-Type': 'application/json'},
'{"Success":true}'
]
);
var callback = this.spy();
functionToTest(callback, callback);
server.respond();
QUnit.ok(callback.calledWith(generateLogMessage('Success')));
});
This test works, but it returns successfully regardless of what the request body. What I want to do is only have the Fake Server respond if the request body is { one: 'one', two: 'two' }