In my AngularJS application, itβs hard for me to understand, like a unit test, that keeping the promise then will change location.url. I have a login function that calls a service, AuthenticationService . It returns a promise, and the fulfillment of the then promise changes location.url.
This is the AuthCtrl controller:
angular .module('bloc1App') .controller('AuthCtrl', ['$scope', '$http','$location', 'AuthenticationService', function($scope, $http, $location, AuthenticationService) { this.AuthenticationService = AuthenticationService; var self = this; $scope.login = function(username, password){ self.AuthenticationService .login(username, password) .then(function(){ $location.url('/tasks'); }); }; } ]);
This is my attempt to use unit test:
describe('Controller: AuthCtrl', function () { var scope, location, route, q, rootScope, AuthCtrl; beforeEach(module('bloc1App')); beforeEach(inject(function($controller, $rootScope, $location, $route, $q) { scope = $rootScope.$new(); q = $q; rootScope = $rootScope; location = $location; route = $route; AuthCtrl = $controller('AuthCtrl', { $scope: scope, $route: route, $location: location }); })); it('login should redirect user to tasks view', function(){ var deferred = q.defer(); spyOn(AuthCtrl.AuthenticationService, 'login').andReturn(deferred.promise); spyOn(location, 'url'); scope.login('foo', 'foo'); deferred.resolve(); scope.$apply(); expect(location.url).toHaveBeenCalledWith('/tasks'); }); });
When I run this test, I get this error. I get the same error if I use rootScope. $ Apply () instead:
Error: Unexpected request: GET views/AuthView.html No more request expected
When I retrieve the scope. $ apply (), I get this error:
Expected spy url to have been called with [ '/tasks' ] but it was never called.
Any ideas on how to fix this? This is the first time that I am checking a promise, and I probably misunderstand how to do this.
Thank you in advance for your help.