【发布时间】:2014-12-14 15:53:10
【问题描述】:
在我的 AngularJS 应用程序中,我无法弄清楚如何对 then promise 的执行更改 location.url 进行单元测试。我有一个函数 login,它调用服务 AuthenticationService。它返回promise,然后promise的执行会改变location.url。
这是控制器AuthCtrl:
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');
});
};
}
]);
这是我在单元测试中的尝试:
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');
});
});
当我运行这个测试时,我得到了这个错误。如果我使用 rootScope.$apply() 代替,我会得到同样的错误:
Error: Unexpected request: GET views/AuthView.html
No more request expected
当我取出 scope.$apply() 时,我得到这个错误:
Expected spy url to have been called with [ '/tasks' ] but it was never called.
关于如何解决这个问题的任何想法?这是我第一次对 Promise 进行单元测试,我可能在概念上误解了如何执行此操作。
提前感谢您的帮助。
【问题讨论】:
标签: angularjs unit-testing jasmine