reactjs - 如何在 JEST 中测试 JSON.parse

标签 reactjs jestjs

我试图使用 JEST 为 React 组件编写单元测试,该组件从 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": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5d29382e291d29382e29733e3230" rel="noreferrer noopener nofollow">[email protected]</a>"
    }
    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)

最佳答案

JSONData 应该是包含 JSON 的字符串,而不是对象

否则 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));

关于reactjs - 如何在 JEST 中测试 JSON.parse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39193533/

相关文章:

javascript - 如何在不渲染组件的情况下传递 Prop ?

reactjs - 查询带有特定文本的按钮

javascript - 使用 jest 测试提交以获取的 FormData

javascript - 在应用程序完全加载后,如何将 Google 跟踪代码管理器加载到 next.js 应用程序?

javascript - react native typescript : Can't find variable: React

javascript - 在 ReactJS 中将连字符写为样式对象时处理 css 样式中的连字符

angular - 使用 { dispatch : false } 进行 NGRX 效果测试

javascript - 在 react 测试渲染器中调用 prop 回调不会更新钩子(Hook)

javascript - 在 Jest 运行所有测试后,如何关闭 node.js 中的 pg-promise 连接?

javascript - Firebase - onAuthStateChanged 2 秒延迟。添加加载文本/微调器