How do I deal with localStorage in jest tests?

后端 未结 17 1786
长情又很酷
长情又很酷 2020-11-28 02:01

I keep getting \"localStorage is not defined\" in Jest tests which makes sense but what are my options? Hitting brick walls.

17条回答
  •  情话喂你
    2020-11-28 02:54

    Currently (Oct '19) localStorage can not be mocked or spied on by jest as you usually would, and as outlined in the create-react-app docs. This is due to changes made in jsdom. You can read about it in the jest and jsdom issue trackers.

    As a workaround, you can spy on the prototype instead:

    // does not work:
    jest.spyOn(localStorage, "setItem");
    localStorage.setItem = jest.fn();
    
    // works:
    jest.spyOn(window.localStorage.__proto__, 'setItem');
    window.localStorage.__proto__.setItem = jest.fn();
    
    // assertions as usual:
    expect(localStorage.setItem).toHaveBeenCalled();
    

提交回复
热议问题