如何在JEST中测试JSON.parse [英] How to test JSON.parse in JEST

查看:213
本文介绍了如何在JEST中测试JSON.parse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用JEST为一个React组件编写单元测试,该组件从componentWillMount函数中的locaStorage获取一个JSON对象,

i was trying to write the unit test using JEST for a react component which gets a JSON Object from locaStorage in componentWillMount function,

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

运行此测试时,出现如下错误,

when i run the this test i get an error as below,

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

推荐答案

JSONData应该是包含JSON的字符串,而不是 object .

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

否则,localStorage.getItem('JSONResponse')返回一个对象.在对象上调用JSON.parse时,该对象将首先转换为字符串"[object Object]",而该字符串显然不是值JSON.

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(…)

似乎最简单的解决方案是调用JSON.stringify:

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

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

这篇关于如何在JEST中测试JSON.parse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆