Skip to content

Instantly share code, notes, and snippets.

@ronapelbaum
Last active July 13, 2016 08:29
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 ronapelbaum/e78e593b86a5e98db3baa0e303e69d9b to your computer and use it in GitHub Desktop.
Save ronapelbaum/e78e593b86a5e98db3baa0e303e69d9b to your computer and use it in GitHub Desktop.
test an angular service with $promise
describe('GreetController spec', function() {
var mockService, deferred, ctrl;
beforeEach(module('MyModule'));
beforeEach(module(function($provide) {
//#1 - mock DataService
mockService = jasmine.createSpyObj('DataService', ['getGreeting']);
$provide.value('DataService', mockService);
}));
beforeEach(inject(function($controller) {
//#2 get an instance of the controller
ctrl = $controller('GreetController');
}));
it('greeting should change after promise resolved', inject(function($q, $rootScope) {
//#3 create promise
deferred = $q.defer();
//mock service response (for controller's constructor)
mockService.getGreeting.and.returnValue(deferred.promise);
//#4 invoke the controller to get the promise
ctrl.initGreeting();
//the data field is not yet initialized
expect(ctrl.greeting).toBeNull();
//#5 resolve the promise
deferred.resolve('Hello World');
//not yet...
expect(ctrl.greeting).toBeNull();
//#6 trigger the digest cycle
//"it's important to know that the resolution of promises is tied to the digest cycle"
$rootScope.$digest();
//now!
expect(ctrl.greeting).toBe('Hello World');
}));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment