How to test JSON.parse in JEST

2019-09-17 20:41发布

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)

1条回答
Bombasti
2楼-- · 2019-09-17 21:21

JSONData should be a string containing JSON, not an object.

Otherwise localStorage.getItem('JSONResponse') returns an object. When calling JSON.parse on an object, the object will be converted to the string "[object Object]" first which clearly isn't value JSON.

> JSON.parse({})
  Uncaught SyntaxError: Unexpected token o in JSON at position 1(…)
> JSON.parse("[object Object]")
  Uncaught SyntaxError: Unexpected token o in JSON at position 1(…)

Seems like the simplest solution would be to call JSON.stringify:

stub.returns(JSON.stringify(JSONData));
查看更多
登录 后发表回答