【发布时间】:2016-12-12 14:33:49
【问题描述】:
angular.module('MyApp')
.controller('loginCtrl', function($scope, $rootScope, $location, $window, $auth) {
$scope.login = function() {
$auth.login($scope.user)
.then(function(response) {
if(response.data.users.status === 'success'){
$rootScope.currentUser = response.data.username;
$window.localStorage.user = JSON.stringify(response.data.users);
$location.path('/');
}
}).catch(function(response){
if(response.data.users.status === 'error'){
$scope.error = response.data.users.error;
}
})
};
});
我得到错误:
users is undefined error
使用 Karma 和 Jasmine 测试上述代码时。
规格如下:
describe('LogController', function() {
var $scope, controller, $location, $window;
beforeEach(module('MyApp'));
beforeEach(inject(function($rootScope, $controller, _$location_ , _$window_ , _$httpBackend_) {
$scope = $rootScope.$new();
$window = _$window_
$httpBackend = _$httpBackend_;
$location = _$location_;
controller = $controller('loginCtrl', {
$scope: $scope,
$location: $location,
$window: $window
});
}))
it('should log in a user and redirect to homepage', function() {
$httpBackend.when('POST','/user/auth').respond(200);
//whitelist all view
$httpBackend.whenGET(/partials.*/).respond(200, '');
$scope.username = 'test';
$scope.password = '123456';
$scope.login();
$httpBackend.flush();
$scope.$apply();
expect($location.path()).toBe('/x');
});
})
什么是users 未定义?以及如何模拟来自 $window.localStorage 的回复,这样它就不会了?
【问题讨论】:
-
错误、代码和预期结果也需要在您的问题中。您不能使用 Pastebin 发布我们需要查看的信息。
-
@GeorgeStocker 谢谢您,先生,但是您对此有答案吗?我被困了好几个小时。
-
您的问题是您需要为您的模拟响应包含一个
data对象,目前您返回一个空字符串:` $httpBackend.whenGET(/partials.*/).respond( 200, '');. That empty string should be a data object:{data: { "users": { "status" : "Worked"} } }` -
在这种情况下我该如何写期望?楼主能回复一下吗?
-
我试过你的答案我仍然得到同样的错误。
标签: javascript angularjs unit-testing jasmine karma-runner