Reputation: 46507
Here's a simple React component with an optional prop with a default value:
class Test extends Component {
static defaultProps = {
role: 'default'
}
render() {
return (
<div role={this.props.role}>
{ this.props.children }
</div>
);
}
}
In the test, I'm mounting this component twice, once omitting the optional prop and once specifying the default value for the prop:
import toJson from 'enzyme-to-json';
import { mount } from 'enzyme';
...
test('should render the same tree', () => {
const a = mount(<Test />);
const b = mount(<Test role="default" />);
expect(toJson(a)).toMatchSnapshot(); // passes
expect(toJson(b)).toMatchSnapshot(); // passes
expect(toJson(a)).toEqual(toJson(b)); // fails
});
Unexpectedly, expect(toJson(a)).toEqual(toJson(b));
is failing. However, Jest confirms that the resulting tree is identical, as it logs the no visual difference
message:
● should render the same tree
expect(received).toEqual(expected)
Expected value to equal:
<Test role="default"><div role="default" /></Test>
Received:
<Test role="default"><div role="default" /></Test>
Difference:
Compared values have no visual difference.
43 | expect(toJson(a)).toMatchSnapshot();
44 | expect(toJson(b)).toMatchSnapshot();
> 45 | expect(toJson(a)).toEqual(toJson(b));
| ^
46 | });
47 |
48 |
Furthermore, as expected, this produces identical snapshots for the case when the optional property is omitted as well as when it's provided with the default value:
exports[`should render the same tree 1`] = `
<Test
role="default"
>
<div
role="default"
/>
</Test>
`;
exports[`should render the same tree 2`] = `
<Test
role="default"
>
<div
role="default"
/>
</Test>
`;
I'm struggling to figure out why this test case is failing.
toJson
utility function from enzyme-to-json
?enzyme
itself?Upvotes: 1
Views: 866
Reputation: 45820
The helper function in enzyme-to-json
is called toJson()
but that is a bit of a misnomer. It doesn't return back JSON, it actually returns back a quite complicated object that the Jest toMatchSnapshot()
then converts into the JSON that ends up in the snapshot file.
The simplified view of the two objects at the highest level returns no visual difference
but if you go one level deeper into the node
key you can start to see the differences:
expect(toJson(a).node).toEqual(toJson(b).node);
Upvotes: 1