Skip to content

Instantly share code, notes, and snippets.

@VivienAdnot
Created September 14, 2016 04:43
Show Gist options
  • Save VivienAdnot/ab0fd4d2a47b20437fd0fedd1f0c2932 to your computer and use it in GitHub Desktop.
Save VivienAdnot/ab0fd4d2a47b20437fd0fedd1f0c2932 to your computer and use it in GitHub Desktop.
Angular Promises Unit test
angular.module('breakmeApp')
.controller('MainCtrl', function($scope, searchService) {
searchService.search($scope.query)
.then(function(data) {
// This is set when the promise is resolved.
$scope.results = data;
})
.catch(function() {
// This is set in the event of an error.
$scope.error = 'There has been an error!';
});
});
angular.module('breakmeApp')
.factory('searchService', function ($q, $http) {
var service = {};
service.search = function search (query) {
// We make use of Angular's $q library to create the deferred instance
var deferred = $q.defer();
$http.get('http://localhost/v1?=q' + query)
.success(function(data) {
// The promise is resolved once the HTTP call is successful.
deferred.resolve(data);
})
.error(function() {
// The promise is rejected if there is an error with the HTTP call.
deferred.reject();
});
// The promise is returned to the caller
return deferred.promise;
};
return service;
});
describe('Testing a Controller that uses a Promise', function() {
var $rootScope;
var $scope;
var $q;
var deferred;
var mockSearchService;
var mockResponse = 123;
beforeEach(module('breakmeApp'));
beforeEach(inject(function(_$q_, _$rootScope_) {
$q = _$q_;
$rootScope = _$rootScope_;
deferred = _$q_.defer();
}));
beforeEach(inject(function($controller, searchService) {
$scope = $rootScope.$new();
// Use a Jasmine Spy to return the deferred promise by mocking the service
spyOn(searchService, 'search').and.returnValue(deferred.promise);
// Init the controller, passing our spy service instance
$controller('MainCtrl', {
$scope: $scope,
searchService: searchService
});
}));
it('should resolve promise', function() {
// Setup the data we wish to return for the .then function in the controller
deferred.resolve(mockResponse);
// We have to call apply for this to work
$scope.$apply();
// Since we called apply, not we can perform our assertions
expect($scope.results).toBe(mockResponse);
expect($scope.error).toBe(undefined);
});
it('should reject promise', function() {
// This will call the .catch function in the controller
deferred.reject();
// We have to call apply for this to work
$scope.$apply();
// Since we called apply, not we can perform our assertions
expect($scope.results).toBe(undefined);
expect($scope.error).toBe('There has been an error!');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment