Jasmine tests for jquery post

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:

So, how do you test this and validate the correct url & data was used?

First, you need to spy on the ajax call:

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:

Leave a Reply

Your email address will not be published.