gpt4 book ai didi

javascript - 如何在 AngularJS 单元测试中 stub `$window.localStorage`?

转载 作者:行者123 更新时间:2023-11-28 05:14:23 28 4
gpt4 key购买 nike

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 的响应,这样就不会出现这种情况?

最佳答案

您应该模拟登录响应 $httpBackend.when('POST','/user/auth').respond(200,mockResponseData);

地点:

mockResponseData = {
“数据”: {
“用户名”:“一些值”,
“用户”:{
“状态”:“成功”
}
}
}

关于javascript - 如何在 AngularJS 单元测试中 stub `$window.localStorage`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41103179/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com