开发者问题收集

AngularJS:TypeError:未定义不是本地存储的对象

2016-06-06
1014

我想测试 localstorage 中的值。这是我用来存储这些值的包: https://www.npmjs.com/package/ngstorage

这是我的代码:

var module = angular.module(‘myModule', ['ngStorage']);
                

 module.controller(‘MyController’, ['$scope', '$localStorage', function($scope,$localStorage){

 $scope.storage = $localStorage;

 $scope.data = {
    
   name: “55 Cherry St.“
 };

 $scope.storage.name = $scope.data.name;
 }]);

我想在 Jasmine 和 Mocha 中测试上述代码。我不知道该怎么做,因为它现在给了我这个错误:

TypeError: undefined is not an object (evaluating 'expect($localStorage).to.be') (line 14)

这是我的测试代码:

describe('my Module', function () {
  var $controller;
  var $scope;
  var element;

  beforeEach(module('myModule'));
  beforeEach(module('ngStorage'));

  beforeEach(function() {
    $scope = {};

    inject(function ($controller, $rootScope, $compile, $localStorage) {
      var $controller = $controller('myController', {$scope: $scope});
    });
  });

  describe('My controller', function () {

    it('should contain a $localStorage service', inject(function(
      $localStorage
    ) {
      expect($localStorage).not.to.equal(null);
    }));
});
});
2个回答

Jasmine 没有 expect('something').not.to.equal() 函数。请使用以下函数:

expect($localStorage).not.toBe(null);

此外,在重现您的错误时, myController 未定义 。使用以下方法修复:

var $controller = $controller('MyController', {$scope: $scope});  // MyController (uppercase)

我认为 beforeEach(module('ngStorage')); 不是必需的,因为它已经是您的模块的依赖项。

slackmart
2016-06-06

您必须为其添加一个变量才能对其进行测试。以下是您需要在代码中做的改进

describe('my Module', function () {
  var $controller;
  var $scope;
  var element;
  var $localStorage;

  beforeEach(module('myModule'));
  beforeEach(module('ngStorage'));

  beforeEach(function() {
    $scope = {};

    inject(function ($controller, $rootScope, $compile, $localStorage) {
      var $controller = $controller('myController', {$scope: $scope, $localStorage: $localStorage});
    });
  });

  describe('My controller', function () {

    it('should contain a $localStorage service', inject(function(
      $localStorage
    ) {
      expect($localStorage).not.to.equal(null);
    }));
});
});

expect(controller.$localStorage).not.to.equal(null); //$localStorage is part of controller now
Arpit Srivastava
2016-06-06