Sunday, August 21, 2011

Jasmine and mock AJAX

Things just keep getting better for me today Smile. Having had a great deal of fun with the nHibernate search I stumbled across a really neat JavaScript testing framework call ‘Jasmine’. Now not to go through the whole blah blah of what ‘Jasmine’ is I would recommend you Google it. Plenty of references to the project there (http://www.mediafly.com/content/exploring-jasmine-bdd-framework-javascript for starters!)

What I would like to point out is the AJAX mock requests and responses. One painful thing about testing JavaScript is the need to manually navigate the site/pages and debug the responses. Personally I like a TDD approach and wanted to try doing the JavaScript development using TDD.

While getting started with ‘Jasmine’ is very simple I did fiddle for an hour or so trying to assimilate the mechanism I was to use in mocking AJAX responses. So below I have listed the steps required to get a basic round trip going. This would reside in the *Spec.js file.

   1: describe("Application", function () {



   2:     var application;



   3:     var profile;



   4:  



   5:     beforeEach(function () {



   6:         application = new Application();



   7:         profile = new Profile();



   8:         spyOn($, "ajax").andCallFake(function (params) {



   9:             params.success('{"IsRegistered" : true}');



  10:         });



  11:     });



  12:  



  13:     it("should be able to register with the site", function () {



  14:         profile.firstName = "firstname";



  15:         profile.lastName = "last";



  16:         profile.email = "email@domain.com";



  17:         profile.birthDate = new Date("2011-04-01");



  18:  



  19:         application.register(profile);



  20:         expect(profile.isRegistered).toEqual(true);



  21:     });



  22: });






And to quickly run through it:




  • beforeEach is the same as SetUp in your standard unit testing frameworks, so here you setup your test case.


  • spyOn is a method declared in the ‘Jasmine’ framework and dictates which class it should ‘spyOn’ and what method it should spyOn in that class.


  • andCallFake is the mechanism that reroutes the AJAX request to the anonymous method declared inside it.


  • params relates back to the jQuery AJAX definition. Via this we can execute the success method and pass in the response data we have manually defined.





Very cool. As this is my initial exploration into ‘Jasmine’ I might very well have got it wrong or there might be a smarter way of doing this but I thought I would share it anyways!





References:



No comments:

Post a Comment