如何在我的AngularJS单元测试中存根`$ window.localStorage`? [英] How do I stub `$window.localStorage` in my AngularJS unit tests?

查看:122
本文介绍了如何在我的AngularJS单元测试中存根`$ window.localStorage`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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测试上面的代码。

when testing above code with Karma and 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'); 
   });

})

什么是用户 undefined?我如何模拟来自 $ window.localStorage 的回复所以它不会?

What is users undefined? And how do I mock out a response from $window.localStorage so it won't be?

推荐答案

你应该模仿登录的响应
$ httpBackend.when('POST','/ user / auth')。respond(200,mockResponseData);

Youshould mock the response for login $httpBackend.when('POST','/user/auth').respond(200, mockResponseData);

其中:

mockResponseData = {
数据:{
用户名:someValue,
用户:{
状态:成功
}
}
}

这篇关于如何在我的AngularJS单元测试中存根`$ window.localStorage`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆