public
Last active

A simple Jasmine Ajax spying example

  • Download Gist
jasmine-ajax-example-spec.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
window.context = window.describe
 
describe ".googlePandaStatus", ->
Given -> @ajaxCaptor = jasmine.captor()
Given -> spyOn($, "get")
When -> googlePandaStatus("Happy")
And -> expect($.get).toHaveBeenCalledWith("http://google.com", @ajaxCaptor.capture())
describe "~ the AJAX success handler", ->
Given -> spyOn(window, "printMessage")
context "a Chinese panda", ->
When -> @ajaxCaptor.value("Chinese")
Then -> expect(printMessage).toHaveBeenCalledWith("Happy Chinese Panda")
context "a Columbus Zoo panda", ->
When -> @ajaxCaptor.value("Columbus Zoo")
Then -> expect(printMessage).toHaveBeenCalledWith("Happy Columbus Zoo Panda")
jasmine-ajax-example.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12
// Production Source
var googlePandaStatus = function(disposition) {
 
var aClosureScopedVar = 'Panda';
 
$.get('http://google.com',function(data) {
printMessage(disposition+' '+data+' '+aClosureScopedVar);
});
 
};
 
var printMessage = function() { /* imagine some terribly complex unrelated component that prints messages*/ }

The purpose of this example is to show how a simple spy (in this case, $.get) can be used to specify asynchronous/ajax code. This approach gives us: (1) synchronous execution, (2) an opportunity to discretely specify many contexts of a callback function using nested example groups, and (3) a spec that can exercise arguments sent to the original function, arguments sent to the callback function, and closure scope variables.

I particularly like this structure because your Jasmine specs can appear symmetrical to your JavaScript. And when the nesting goes too deep for comfort, it's a healthy pressure to start extracting new responsibilities.

I just updated the spec code to do a few things (all of which are more typical of how I write specs now). They use:

  1. CoffeeScript
  2. jasmine-given
  3. jasmine-stealth

As a result, the spec is now 18 lines (before, it had been 38 lines)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.