i was trying to write the unit test using JEST for a react component which gets a JSON Object from locaStorage in componentWillMount function,
React component
import React from 'react';
export default class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
sampJSON: null,
username: null
}
}
componentWillMount(){
this.setState({
sampJSON: JSON.parse(localStorage.getItem('JSONResponse') || '{}');
});
this.setState({
username: sampJSON.username
});
}
render(){
return(){
<div>
<h1> Hi {this.state.username} </h1>
</div>
}
}
}
and here is my test code,
import React from 'react';
import sinon from 'sinon';
import Testing from './Testing.js';
import TestUtils from 'react-addons-test-utils';
jest.dontMock('Testing');
jest.dontMock('sinon');
describe('Testing Testing component', () => {
var JSONData = {
"username" : "Testing",
"surName" : "surName",
"email": "test@test.com"
}
beforeEach(function() {
// window.localStorage.setItem
var spy = sinon.spy(window.localStorage, "setItem");
// You can use this in your assertions
spy.calledWith('aKey', JSONData)
});
it('renders the Testing',() => {
var stub = sinon.stub(window.localStorage, "getItem");
stub.returns(JSONData);
var testCmp = TestUtils.renderIntoDocument(<Testing />);
expect(testCmp).toBeDefined();
});
});
when i run the this test i get an error as below,
- SyntaxError: Unexpected token o
at Object.parse (native)
JSONData
should be a string containing JSON, not an object.Otherwise
localStorage.getItem('JSONResponse')
returns an object. When callingJSON.parse
on an object, the object will be converted to the string"[object Object]"
first which clearly isn't value JSON.Seems like the simplest solution would be to call
JSON.stringify
: