Prasadau
Prasadau

Reputation: 61

How can we unit test the sessionstorage in Angular?

I am new to unit testing in Angular, and I am trying to test the sessionstorage and localstorage.

My code is:

subscribe(data) {
        sessionStorage.setItem('myProductDetail', JSON.stringify(data));
    }

subscribe(data) {
        LocalStorage.setItem('dummyname', data[0].name);
    }

Is it a good practice to do unit testing for session, local storage and private classes?

I am trying to follow the example code below to mock my localstorage and sessionstorage.

beforeEach(function () {
  var store = {};

  spyOn(localStorage, 'getItem').andCallFake(function (key) {
    return store[key];
  });
  spyOn(sessionStorage, 'setItem').andCallFake(function (key, value) {
    return store[key] = value + '';
  });
  spyOn(localStorage, 'clear').andCallFake(function () {
      store = {};
  });
});

Any guidance is greatly appreciated.

Upvotes: 1

Views: 15489

Answers (1)

ainlolcat
ainlolcat

Reputation: 554

See thread https://github.com/jasmine/jasmine/issues/299 for more detail about differences in browsers.

Method 0:

Leave as is. Firefox or phantomjs will setup storage and you can check value in storage after. If You still need custom reaction You can spy on it in beforeEach section.

Method 1: just spy on sessionStorage.
Works with phantomjs and may be chrome but does not in FF.

const store = {};
spyOn(sessionStorage, 'getItem').and.callFake((key) => {
  return store[key];
});
spyOn(sessionStorage, 'setItem').and.callFake((key, value) => {
  console.log(key);
  return store[key] = value + '';
});

Method 2: replace sessionStorage.
Will work in firefox but not in phantomjs because it prohibits sessionStorage replacement. But phantomjs allows to spy on it so method 1 will work.

const mock = (() => {
  let store = {};
  return {
    getItem: (key) => {
      return store[key];
    },
    setItem: (key, value) => {
      console.log(key);
      store[key] = value + '';
    },
    clear: () => {
      store = {};
    }
  };
})();
Object.defineProperty(window, 'sessionStorage', { value: mock, writable: true });

Method 3: spy on Storage.prototype.
Will work on all implementation but replaces all storages.

spyOn(Storage.prototype, 'setItem').and.callFake((key, value) => {
  console.log(key);
  // some logic like in prev examples
});
// other spyOn

You can combine method 1 and 2 like author of this post did for prev version https://blog.bradleygore.com/2014/09/17/angular-unit-testing-pt-1-local-storage/.

Upvotes: 6

Related Questions