Skip to content

Instantly share code, notes, and snippets.

@pablojim
Last active December 27, 2015 00:49
Show Gist options
  • Save pablojim/7240847 to your computer and use it in GitHub Desktop.
Save pablojim/7240847 to your computer and use it in GitHub Desktop.
angular.module('myApp.controllers', [])
.controller('MyCtrl', ['$scope', 'MyService', function ($scope, MyService) {
//Get promise and once resolved set it in the scope
MyService.fetchData('foo').then(function(result) {
$scope.result = result;
});
}]);
describe('myApp', function () {
var scope,
controller,
service;
beforeEach(function () {
module('myApp.controllers');
});
// Mock service
beforeEach(module(function ($provide) {
service = {fetchData: jasmineNG.createPromiseReturningSpy("RESULT")}
$provide.value('MyService', service);
}));
describe('MyCtrl', function () {
beforeEach(inject(function ($rootScope, $controller, $q) {
//IMPORTANT! set $q on the test helper
jasmineNG.$q = $q;
scope = $rootScope.$new();
controller = $controller('MyCtrl', {
'$scope': scope
});
}));
it('should call service and set result on scope', function () {
expect(scope.result).not.toBeDefined();
expect(service.fetchData).toHaveBeenCalledWith('foo');
//Call apply to propogate changes
scope.$apply();
expect(scope.result).toBe('RESULT');
});
});
});
jasmineNG = {};
//set $q in your test
jasmineNG.$q = null;
//Could make similar to test a failing promise
jasmineNG.createPromiseReturningSpy = function(retval) {
return jasmine.createSpy().andCallFake(function() {
res = jasmineNG.$q.defer();
res.resolve(retval)
return res.promise
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment