Jasmine 2.x Mock Local Storage
This will add two functions mockLocalStorage()
and unmockLocalStorage()
Install
npm install --save-dev jasmine-local-storage
// in your jasmine helpers file
require("jasmine-local-storage");
Usage
beforeEach(function () {
mockLocalStorage();
});
it("will not write to actual localStorage", function () {
unmockLocalStorage();
localStorage.setItem("test", 1);
expect(localStorage.getItem("test")).toBe("1");
mockLocalStorage();
localStorage.setItem("test", 2);
expect(localStorage.getItem("test")).toBe("2");
expect(localStorage.key(0)).toBe("test");
localStorage.removeItem("test");
expect(localStorage.getItem("test")).toBe(null);
expect(localStorage.setItem).toHaveBeenCalledTimes(1);
expect(localStorage.getItem).toHaveBeenCalledTimes(1);
expect(localStorage.removeItem).toHaveBeenCalledTimes(1);
expect(localStorage.key).toHaveBeenCalledTimes(1);
expect(localStorage.clear).toHaveBeenCalledTimes(0);
unmockLocalStorage();
expect(localStorage.getItem("test")).toBe("1");
localStorage.removeItem("test");
});