Wednesday, June 26, 2013

Jasmine Jquery Spies and Mocks

In the previous post we have seen how to get started with Jasmine by testing a simple function that validates an email address.
But most of the time we want to test JS that runs inside the browser and interacts with the DOM.
We also want to test Ajax calls and mocking the output from the server, which of course is not running during the tests.

You will usually interact with the DOM using some library like JQuery.
Using Jasmine-JQuery you can integrate it easily with Jasmine.
For mocking server response instead Jasmine Spies comes in very handy.

Suppose we keep the same folder structure as in the previous example.
Of course we need to download JQuery and JQuery-Jasmine, place them respectively under src and lib, finally add the following 2 lines to the head section in SpecRunner.html after the jasmine imports:


  1. <script type="text/javascript" src="lib/jasmine-jquery.js"></script>  
  2. <script type="text/javascript" src="src/jquery-1.5.1.min.js"></script>  
So let's test a JQuery plugin which downloads from the server an html snippet containing some list of friends and set it as Html of each element in the JQuery's wrapped set of elements.

  1. $(function(){  
  2.   jQuery.fn.addFriendList = function(){  
  3.     var that = this;  
  4.     $.ajax({  
  5.       url:          'friends',  
  6.       type:         'GET',  
  7.       contentType:  'application/json',  
  8.       dataType:     'json',  
  9.       success: function(html){  
  10.               $(that).html(html);  
  11.            }  
  12.     });  
  13.   }  
  14. });  
This code goes inside src/demo.js, while the test has to be placed inside spec/demo_spec.js

  1. describe("Download friends"function() {  
  2.   
  3.   it("should get the list of friends and insert it in the page",function(){  
  4.     setFixtures('<div id="friends"></container>');  
  5.     spyOn(jQuery,'ajax');  
  6.     $('#friends').addFriendList();  
  7.     jQuery.ajax.mostRecentCall.args[0].success('<ul><li>Arturo</li><li>Concetto</li></ul>');  
  8.     expect($('#friends li').length).toBe(2);  
  9.   });  
  10.   
  11. });  

So let's see step by step what we is happening here:
  • first we define our test suite by calling describe()
  • a call to it() define our test which "should get the list of friends and insert it in the page"
  • setFixtures() comes from Jasmine-JQuery and allows you to insert html into the SpecRunner's DOM. While setFeatures() takes as input a string, loadFixtures() load the html from an external file whose path has passed to loadFixtures(). The default path is spec/javascript/fixtures. But since our test is very simple I preferred using the inline version and to just add a div to the page
  • spyOn(jQuery,'ajax') allows us to "spy" on any call to ajax()
  • $('#friends').addFriendList() just calls our plugin
  • mostRecentCall is one the fields in jasmine.Spy, it gives access to the last call to the spied method. In this case we are calling the success callback with a mocked html.
  • finally we check the div has been modified correctly. Actually a lot of expectations come with Jasmine-JQuery but in this case I preferred not to use any

Spies are in my opinion the greatest feature in Jasmine, the following functions facilitate mocking:
  • andCallFake(fakeFunction), andReturn(), andThrow() basically allows you to determine the output from a call to the spied function
  • andCallThrough() calls the original implementation and it is useful if you want to just verify functions calls

It is indeed possible to verify function calls using the following matchers:
  • toHaveBeenCalled() and toHaveBeenCalledWith() verifies a function has been called (and with what parameters)
  • wasNotCalled() and wasNotCalledWith() verifies a function has not been called (and with what parameters)

One last feature I have not covered in these posts are Asynchronous Specs, which come handy if you want to simulate different asynchronous events occurring in different order.

No comments:

Post a Comment