【问题标题】:How do I stub `$window.localStorage` in my AngularJS unit tests?如何在 AngularJS 单元测试中存根“$window.localStorage”?
【发布时间】: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


【解决方案1】:

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

地点:

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

【讨论】:

    猜你喜欢
    • 2014-05-15
    • 2016-02-12
    • 1970-01-01
    • 2012-04-12
    • 2019-01-07
    • 2016-02-17
    • 2013-12-13
    • 1970-01-01
    • 2016-01-05
    相关资源
    最近更新 更多