如何在JEST中测试JSON.parse

时间:2016-08-28 16:41:40

标签: reactjs jestjs

我正在尝试使用JEST编写单元测试,用于在componentWillMount函数中从locaStorage获取JSON对象的react组件,

反应组件

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>
        }
    }
}   

这是我的测试代码,

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();
    });
});

当我运行此测试时,我收到如下错误,

- SyntaxError: Unexpected token o
        at Object.parse (native)

1 个答案:

答案 0 :(得分:2)

req.user应该是包含JSON的字符串,而不是对象

否则JSONData会返回一个对象。在对象上调用localStorage.getItem('JSONResponse')时,该对象将首先转换为字符串JSON.parse,这显然不是值JSON。

"[object Object]"

似乎最简单的解决方案是致电> 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(…)

JSON.stringify