fscore fscore - 5 months ago 72
Javascript Question

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

Answer

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.

Comments