vendredi 17 novembre 2017

Why we need toJSON when comparing to two components equality?

I write component which convert text with \n line break to html paragraph

Text.js

const Text = props => ((
  <div>
    { props.paragraph.split('\n').map((line, index) => {
      if (line.length === 0) return;
      return <p key={index}>{ line }</p>;
    })}
  </div>
)
);

When I want to compare to Components, there is error if I call it without toJSON to rendered Component. (Even though result is the same when I check with toMatchSnapshot())

Text.spec.js

it('ignores \\n at last', () => {
  const paragraphA = 'aa\nbbb\n';
  const paragraphB = 'aa\nbbb';
  const cA = renderer.create(<Text paragraph={paragraphA} />);
  const cB = renderer.create(<Text paragraph={paragraphB} />);
  expect(cA).toEqual(cB); // NG
  expect(cA.toJSON).toEqual(cB.toJSON); // OK
});

jest tells Difference as below

Compared values serialize to the same structure. Printing internal object structure without calling toJSON instead.

I google it but could not find any clue about toJSON

  • Why do we need toJSON here?
  • what toJSON do generally?
  • Where can I find reference about toJSON?

Env

react: 16.1 jest-cli": "^21.2.1"

Thanks in advance!!

Aucun commentaire:

Enregistrer un commentaire