我试图使用 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/