如何在我的AngularJS单元测试中存根`$ window.localStorage`?

时间:2016-12-12 14:33:49

标签: javascript angularjs unit-testing jasmine karma-runner

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的回复,以便它不会成为?

1 个答案:

答案 0 :(得分:0)

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

其中:

mockResponseData = { "data": { "username": "someValue", "users": { "status": "success" } } }