Testing functions that use local storage with Jest

Testing functions that use the browsers local storage API seems easy when you know how. Here's a quick run down on how to mock it out with Jest if, like me, you're not familiar with how to test it. In the end it's very little code. Consider the following TypeScript code.

 import { get, save, key } from "./storage";  
 describe(save, () => {  
  let setItem: jest.Mock;  
  beforeEach(() => {  
   setItem = jest.fn();  
   Storage.prototype.setItem = setItem;  
  it("should call set item with predefined key and json object", () => {  
   const valueToStore = { value: "toStore" };  
   expect(setItem).toHaveBeenCalledWith(key, JSON.stringify(valueToStore));  

The key lines are in the beforeEach call where the setItem function of the Storage prototype is assigned to an instance of jest.fn(). This allows us to make assertions on what is passed to the local storage setItem API.


Popular posts from this blog

Solving `Empty reply from server` in DotNet Core

Windows 8.1 on Minnow Board Max

Middle Stack Developer