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.
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:and this seemed to resolve my issue. Hope this helps.