Jasmine is a js framework that allows behaviour driven testing of Javascript components. One challenge I ran into was how to setup the tests in order to mock jQuery.post(…) calls.
An example of the code for making the call is:
1 2 3 4 5 6 |
$.post(url, JSON.stringify({ "value": "1", "another_value": true }) ).done(function (data) { handleApiResponse(data); }).fail(function (data) { handleFailedApiResponse(data); }); |
So, how do you test this and validate the correct url & data was used?
First, you need to spy on the ajax call:
1 2 3 4 5 |
spyOn($, "ajax").andCallFake(function (options) { var d = $.Deferred(); d.resolve({}); return d.promise(); }); |
The interesting thing to note, even though you are calling $.post, you need to spy on $.ajax
If you want to force the .fail() state of the code then you can use d.reject(). See http://api.jquery.com/category/deferred-object/ for more alternatives.
When you then verify the valid behaviour, you can check eg:
1 2 3 4 5 6 7 |
var data = { "value": "1", "another_value": true }; ... expect($.ajax.mostRecentCall.args[0]["type"].toUpperCase()).toEqual("POST"); expect($.ajax.mostRecentCall.args[0]["url"]).toEqual(url); if (data) { expect($.ajax.mostRecentCall.args[0]["data"]).toEqual(data); } |