title: what is the best way to mock window.sessionStorage in jest
body: <p>Below is a very simple jest unit test and when running it, you will get error like</p>
  <blockquote>
  <p>Cannot spyOn on a primitive value; undefined given</p>
  <p>TypeError: Cannot read property 'getItem' of undefined</p>
  </blockquote>
  <p>but according to the last two comments of <a href="https://github.com/facebook/jest/issues/2098" rel="noreferrer">this post</a>, localStorage and sessionStorage were already added to latest JSDOM and jest. If using <a href="https://www.npmjs.com/package/jest-localstorage-mock" rel="noreferrer">jest-localstorage-mock</a> and add it to my jest setupFiles then you will see weird error like</p>
  <blockquote>
  <p>TypeError: object[methodName].mockImplementation is not a function</p>
  </blockquote>
  <p>So my question is what's the best way to mock localStorage/sessionStorage in jest. Thanks</p>
  <pre><code>describe('window.sessionStorage', () =&gt; {
      let mockSessionStorage;
      beforeEach(() =&gt; {
          mockSessionStorage = {};
          jest.spyOn(window.sessionStorage, &quot;getItem&quot;).mockImplementation(key =&gt; {
              return mockSessionStorage[key];
          });
      });
  
      describe('getItem-', () =&gt; {
          beforeEach(() =&gt; {
              mockSessionStorage = {
                  foo: 'bar',
              }
          });
  
          it('gets string item', () =&gt; {
              const ret = window.sessionStorage.getItem('foo');
              expect(ret).toBe('bar');
          });
      });
  });
  </code></pre>
  <p>Below is my jest config</p>
  <pre><code>module.exports = {
      verbose: true,
      //setupFiles: [&quot;jest-localstorage-mock&quot;],
      testURL: &quot;http://localhost/&quot;
  };
  </code></pre>