AngularJS: TypeError: undefined is not an object for localstorage

AngularJS: TypeError: undefined is not an object for localstorage

我想测试 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 and 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);
    }));
});
});

Jasmine 没有 expect('something').not.to.equal() 功能。改用这个:

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

此外,在重现您的错误时,myController is not defined。固定使用:

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

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

您必须为其添加一个变量才能测试it.Below是您需要在代码中做的改进

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