Skip to content

Instantly share code, notes, and snippets.

@searls
Created April 28, 2011 16:32
Show Gist options
  • Save searls/946704 to your computer and use it in GitHub Desktop.
Save searls/946704 to your computer and use it in GitHub Desktop.
A simple Jasmine Ajax spying example
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")
// 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*/ }
@searls
Copy link
Author

searls commented Mar 5, 2012

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)

@branchgabriel
Copy link

What if your function arg we are capturing has multiple args?
Is there a way to add an array of values for the captured callback? The singular arg only approach only makes this useful some of the time.

When rendering templates with template engines like dust for example. I want to use my captor on the render call. The callback requires err and out arguments. Setting the value of the captor seems like it can't deal with multiple args. I have tried myCaptor.value([arg1, arg2]) but it doesn't seem to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment