/ / Como testar o JSON.parse no JEST - reactjs, jestjs

Como testar o JSON.parse no JEST - reactjs, jestjs

Eu estava tentando escrever o teste de unidade usando o JEST para um componente de reagir que recebe um objeto JSON de locaStorage na função componentWillMount,

Reagir componente

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>
}
}
}

e aqui está o meu código de teste

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

Quando eu executo o teste, recebo um erro como abaixo,

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

Respostas:

1 para resposta № 1

JSONData devia ser um corda contendo JSON, não um objeto.

De outra forma localStorage.getItem("JSONResponse") retorna um objeto. Ao chamar JSON.parse em um objeto, o objeto será convertido para a string "[object Object]" primeiro que claramente não é o valor 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(…)

Parece que a solução mais simples seria chamar JSON.stringify:

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