Skip to content

Instantly share code, notes, and snippets.

@dylansmith
Last active August 29, 2015 14:19
Show Gist options
  • Save dylansmith/b61d9272400d169f9364 to your computer and use it in GitHub Desktop.
Save dylansmith/b61d9272400d169f9364 to your computer and use it in GitHub Desktop.
Test helpers to detect & automatically hand-crank your asynchronous Angular test using $rootScope.$digest()
// see: http://jsbin.com/gipiyi/1/edit?js,output
// App code:
// =========
var app = angular.module('app', []);
app.factory('HodorFactory', function($q) {
return {
isHodor: function() {
return $q(function(resolve) {
resolve('HODOR!');
});
}
};
});
// Test helpers:
// =============
// create a new asyncIt() method that hand-cranks the
// digest loop after calling the test function.
_it = it;
asyncIt = function(description, testFn) {
_it(description, function(done) {
testFn(done);
inject(function($rootScope) {
$rootScope.$digest();
});
});
};
// wrap it() to detect if the test function has a
// 'done' argument & assumes async if so.
it = function(description, testFn) {
var isAsync = testFn.length >= 1;
var fn = isAsync ? asyncIt: _it;
fn(description, testFn);
};
// Tests:
// ======
describe('HodorFactory', function() {
var factory;
beforeEach(module('app'));
beforeEach(inject(function(HodorFactory) {
factory = HodorFactory;
}));
it('#isHodor() should respond with HODOR! (it)', function(done) {
factory.isHodor().then(function(response) {
expect(response).toEqual('HODOR!');
done();
});
});
asyncIt('#isHodor() should respond with HODOR! (asyncIt)', function(done) {
factory.isHodor().then(function(response) {
expect(response).toEqual('HODOR!');
done();
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment