【问题标题】:How to test JSON.parse in JEST如何在 JEST 中测试 JSON.parse
【发布时间】:2017-01-04 17:37:06
【问题描述】:

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

反应组件

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)

【问题讨论】:

    标签: reactjs jestjs


    【解决方案1】:

    JSONData 应该是一个包含 JSON 的 string,而不是 object

    否则localStorage.getItem('JSONResponse') 返回一个对象。在对象上调用JSON.parse 时,对象将首先转换为字符串"[object Object]",这显然不是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(…)
    

    似乎最简单的解决方案是致电JSON.stringify

    stub.returns(JSON.stringify(JSONData));
    

    【讨论】:

    • 您好,感谢您的回复,它确实有效。我能够成功地测试它:)
    猜你喜欢
    • 2020-06-12
    • 2017-12-14
    • 1970-01-01
    • 2018-07-06
    • 2019-04-13
    • 1970-01-01
    • 2020-05-29
    • 2021-12-30
    • 2020-01-05
    相关资源
    最近更新 更多