Skip to content

Instantly share code, notes, and snippets.

@leohemsted
Created March 9, 2016 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leohemsted/2028a0b2d64793ac3938 to your computer and use it in GitHub Desktop.
Save leohemsted/2028a0b2d64793ac3938 to your computer and use it in GitHub Desktop.
A quick example of how to test a function (make_ajax_request) that does some set-up, then calls an ajax request with some deferred handlers defined
define(function(require) {
'use strict';
var $ = require('jquery'),
Sinon = require('sinon');
var always_count, done_count, fail_count;
var make_ajax_request = function() {
always_count = 0;
done_count = 0;
fail_count = 0;
$.ajax({
method: 'post',
url: 'my_url',
contentType: 'application/json'
}).always(function(data, textStatus, jqXHR) {
always_count++;
}).done(function(data, textStatus, jqXHR) {
done_count++;
}).fail(function(data, textStatus, jqXHR) {
fail_count++;
});
};
describe('make_ajax_request', function(){
beforeEach(function(){
// reset counts
always_count = done_count = fail_count = undefined;
// stub out ajax to return a promise (we'll resolve it later in nested describes)
this.d = $.Deferred();
this.ajax_stub = Sinon.stub($, 'ajax').returns(this.d);
// CALL
make_ajax_request();
});
afterEach(function(){
this.ajax_stub.restore();
});
// we haven't triggered the promise yet, just the initial code flow
it('should reset the counts before ajaxing', function(){
expect(always_count).toBe(0);
expect(done_count).toBe(0);
expect(fail_count).toBe(0);
});
describe('when ajax succeeds', function(){
beforeEach(function(){
// we've already called the function - it's finished executing, but the promise
// response handlers haven't happened yet. Lets resolve the promise and watch them fly
this.d.resolve('data', 'textStatus', 'jqXHR');
});
it('should increment always and done counts', function(){
expect(always_count).toBe(1);
expect(done_count).toBe(1);
expect(fail_count).toBe(0);
});
});
describe('when ajax fails', function(){
beforeEach(function(){
// reject will call fail instead of done
this.d.reject('data', 'textStatus', 'jqXHR');
});
it('should increment always and fail counts', function(){
expect(always_count).toBe(1);
expect(done_count).toBe(0);
expect(fail_count).toBe(1);
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment