简体   繁体   中英

AngularJS: TypeError: undefined is not an object for localstorage

I want to test the values in localstorage . Here is the package I use to store those values: https://www.npmjs.com/package/ngstorage

Here is my code:

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

I want to test the above code in Jasmine and Mocha . I dont know how I can as it gives me this error now:

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

Here is my test code:

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 doesn't have a expect('something').not.to.equal() function. Use this instead:

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

Also, while reproducing your error, myController is not defined . Fixed using:

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

And I think beforeEach(module('ngStorage')); is not necessary, since it already is a dependency of your module.

You have to add a variable for it in order to test it.Below is the improvement you need to do in your code

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

OR

expect(controller.$localStorage).not.to.equal(null); //$localStorage is part of controller now

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM