spying on Localstorage in Angular 2 Unit Tests

A quick way to mock localstorage in unit tests

Posted on February 8, 2017

Tags:

Angular

1) Add a spy within your beforeEach method.

spyOn(window.localStorage, 'getItem').and.callFake(function() {
			return JSON.stringify({"test":"test"});
		});

2) Test that localStorage.getItem has been called.

expect( window.localStorage.getItem ).toHaveBeenCalled();