【发布时间】: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)
【问题讨论】: