How Snapshot testing works and what does toMatchSnapshot( ) function do in Jest Snapshot testing for React components? How Snapshot testing works and what does toMatchSnapshot( ) function do in Jest Snapshot testing for React components? reactjs reactjs

How Snapshot testing works and what does toMatchSnapshot( ) function do in Jest Snapshot testing for React components?


I think this question has not been answered with enough details!Snapshot testing is based on history of your previous tests. When you first run a snapshot test it creates a text file including the textual render of your component tree. For example the following test:

import React from 'react';import renderer from 'react-test-renderer';it('renders correctly', () => {  const tree = renderer    .create(<Link page="http://www.facebook.com">Facebook</Link>)    .toJSON();  expect(tree).toMatchSnapshot();});

Will generate the following text file:

exports[`renders correctly 1`] = `<a  className="normal"  href="http://www.facebook.com"  onMouseEnter={[Function]}  onMouseLeave={[Function]}>  Facebook</a>`;

You need to keep these snapshot files in your VCS (git). When you make a change you can run these tests to see if it yet matches the snapshot text file or not.

for more reading study this document: https://jestjs.io/docs/en/snapshot-testing


Snapshots allows you to test if your component renders correctly so in your case

expect(Wrapper).toMatchSnapshot()

If you want to test the number of occurence of a given component, import your second component and create your test:

it("displays the result", () => {  const test = Wrapper.find(Second_Component).length;  expect(test).toEqual(1); // or the number of occurrence you're expecting});

If you're interested in JSON representation of your components you can use the enzyme-to-json package which serves this purpose