私はcomponentWillMount関数でlocaStorageからJSONオブジェクトを取得する反応コンポーネントのためにJESTを使用して単体テストを作成しようとしていましたが、
反応成分
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)
回答:
回答№1は1JSONData
〜する必要があります 文字列 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));