Mocking sessionStorage when using jestjs
Asked Answered
B

5

12

Ok, so I have this simple example React component that interacts with sessionStorage:

//App.jsx    
var React = require('react/addons');

var App = React.createClass({
  handleSubmit: function (e) {
  },

  handleNameChange: function (e) {
    sessionStorage.setItem('name', e.target.value);
  },

  render: function () {
    return (
      <form>
      <input type='text' label='Name' onChange={this.handleNameChange}/>
      <button type='submit' label='Submit' onClick={this.handleSubmit}/>
      </form>
    );
  }
});

module.exports = App;

I've written this test for it using Jest...

//App-test.js
jest.dontMock('../App.jsx');
jest.setMock('sessionStorage', require('../__mocks__/sessionStorage.js'));
describe('App', function () {
  var React = require('react/addons');
  var sessionStorage = require('sessionStorage');
  var App = require('../App.jsx');
  var TestUtils = React.addons.TestUtils;

  var testapp = TestUtils.renderIntoDocument(
    <App />
  );
  var input = TestUtils.findRenderedDOMComponentWithTag(testapp, 'input');

  it('starts with empty value for name input', function () {
    expect(input.getDOMNode().textContent).toEqual('');
  });

  it('updates sessionStorage on input', function () {
    console.log(typeof sessionStorage);
    TestUtils.Simulate.change(input, {target: {value: 'Hello!'}});
    expect(sessionStorage.getItem('name')).toEqual('Hello!');
  });
});

and I've manually mocked sessionStorage in this last code snippet:

//sessionStorage.js
var sessionStorage = {
  storage: {},
  setItem: function (field, value) {
    this.storage.field = value;
  },
  getItem: function (field) {
    return this.storage.field;
  }
};
module.exports = sessionStorage;

The problem is, when I try to run the test, it still complains that sessionStorage is undefined. Even the call to console.log near the end of the test confirms that it is defined, but the error is thrown on the line immediately following. What am I missing here? You can clone the full project from here to see the directory structure, etc.

Brom answered 11/6, 2015 at 21:51 Comment(3)
You are not requiring sessionStorage in App.jsx. How are you referencing it? I believe that Jest injects when you use require.Whiteness
Hey, I am facing the same issue. Did you find a solution?Randazzo
This answer worked for me: https://mcmap.net/q/431093/-what-is-the-best-way-to-mock-window-sessionstorage-in-jestLatia
M
19

To solve this problem across all test cases I used this:

npm install mock-local-storage --save-dev

and then in you, package.json under jest configuration:

  ...
  "jest": {
    ...
    "setupFilesAfterEnv": ["mock-local-storage"]
  }
  ...

This will add mocked localStorage and sessionStorage for all test cases, you do not need changes in every file. Instead of using npm package, you can also put your code in a file and specify file-location here under setupTestFrameworkScriptFile.

Your code should be similar to : https://github.com/letsrock-today/mock-local-storage/blob/master/src/mock-localstorage.js

Mill answered 9/3, 2017 at 21:28 Comment(2)
as an update to this: "setupTestFrameworkScriptFile" has been deprecated and replaced with "setupFilesAfterEnv", which accepts an array of strings rather than a single string. See: github.com/mozilla/addons-frontend/issues/7506Heartstricken
Defining setupTestFrameworkScriptFile on package.json will throw an error for the CRA applications. Therefore you can import it as import 'mock-local-storage' in setupTests.ts.Amabel
I
13

I am not injecting sessionStorage neither. I was able to mock the global variable on the beforeEach function:

 beforeEach(function() {
       ...
       global.sessionStorage = jest.genMockFunction();
       global.sessionStorage.setItem = jest.genMockFunction();
       global.sessionStorage.getItem = jest.genMockFunction();
       ...
     }
Impolicy answered 9/11, 2015 at 3:40 Comment(0)
A
3

Going off the submission from Vishal, I installed the package:

npm install mock-local-storage --save-dev

But my setup was a little different so I added the equivalent to my jest.config.js file:

...
setupFiles: [
    "mock-local-storage",
    ...
]
...

and this seemed to resolve my issue. Hope this helps.

Arjun answered 21/10, 2019 at 20:20 Comment(0)
A
0

Taking @afcastano solution ahead

If you want to spy storage and check the value

 beforeEach(function () {
...
  jest.spyOn(window.sessionStorage, 'setItem');
...
}

it('check storage value', () => {
  expect(window.sessionStorage.setItem).toHaveBeenCalledWith('storage-key', 'storage-value');
});
Allyn answered 9/7, 2021 at 11:18 Comment(0)
T
0

This worked for me in the context of using jest:

beforeAll(() =>
    sessionStorage.setItem(
        KeyStorage.KEY_NAME,
        JSON.stringify([Permission.VALUE_])
    )
);

afterAll(() => 
    sessionStorage.removeItem(KeyStorage.CONTEXT_TYPE_GLOBAL_PERMISSIONS)
);

From my understand, jest was built on top of jasmine, and jasmine allowed some form of interaction with the Browser API, hence, we need not create a storage mock from scratch.

Tyrr answered 13/2, 2023 at 2:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.