I have a JavaScript function that sends a message to the remote API that I am looking for to write unit test for. The method I want to test is as follows:
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 using Sinon.js) that checks if the callback is correct 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 successfully returns no matter what the request body is. I want only Fake Server to respond if the request body is { one: 'one', two: 'two' }
javascript unit-testing qunit sinon
BeardedCoder
source share