How do I stub `$window.localStorage` in my AngularJS unit tests?

北城余情 提交于 2019-12-10 11:39:44

问题


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;
          }
        })
    };
  });

I get the error:

users is undefined error 

when testing above code with Karma and Jasmine.

The spec is below:

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'); 
   });

})

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


回答1:


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

where:

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



来源:https://stackoverflow.com/questions/41103179/how-do-i-stub-window-localstorage-in-my-angularjs-unit-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!