tanmay tanmay - 1 month ago 10
Javascript Question

How to unit-test an AngularJS service that uses localStorage internally

How do I unit-test a factory that uses

$window.localStorage
internally using Jasmine and ngMock?

Here's something similar to what I have:

myApp.factory('myData',function ($window) {
return {
message: $window.localStorage['stuff']
}
});


Thanks a bunch!

Answer

The following works with Jasmine 2.4:

angular.module('MyModule', []).factory('myData',function ($window) {
    return { 
        message: function(){
          return $window.localStorage['stuff'] ;
        }
    }
});

describe("TestName", function() {
  beforeEach(module('MyModule'));
  var myData, store;
  beforeEach(inject(function(_myData_) {
    myData = _myData_;
    store = {};
    var localStorage = window.localStorage;
    spyOn(localStorage, 'getItem').and.callFake(function (key) {
      return store[key];
    });
    spyOn(localStorage, 'setItem').and.callFake(function (key, value) {
      return store[key] = value + '';
    });
    spyOn(localStorage, 'clear').and.callFake(function () {
      store = {};
    });
  }));

  it("feature desc", function() {
    localStorage['stuff'] = 'hello';
    expect(myData.message()).toEqual('hello');
  });
});

Note use of the _myData_ underscore trick (see docs).