Snapshot Testing

(https://reactjs.org/docs/testing-recipes.html#snapshot-testing)

Frameworks like Jest also let you save “snapshots” of data with toMatchSnapshot / toMatchInlineSnapshot. With these, we can “save” the rendered component output and ensure that a change to it has to be explicitly committed as a change to the snapshot.

In this example, we render a component and format the rendered HTML with the pretty package, before saving it as an inline snapshot:


RESETRUNFULL
// hello.test.js, againimport React from "react";import { render, unmountComponentAtNode } from "react-dom";import { act } from "react-dom/test-utils";import pretty from "pretty";import Hello from "./hello";let container = null;beforeEach(() => {  // setup a DOM element as a render target
  container = document.createElement("div");
  document.body.appendChild(container);});afterEach(() => {  // cleanup on exiting
  unmountComponentAtNode(container);
  container.remove();
  container = null;});it("should render a greeting", () => {
  act(() => {
    render(<Hello />, container);
  });
  expect(
    pretty(container.innerHTML)
  ).toMatchInlineSnapshot(); /* ... gets filled automatically by jest ... */
  act(() => {
    render(<Hello name="Jenny" />, container);
  });
  expect(
    pretty(container.innerHTML)
  ).toMatchInlineSnapshot(); /* ... gets filled automatically by jest ... */
  act(() => {
    render(<Hello name="Margaret" />, container);
  });
  expect(
    pretty(container.innerHTML)
  ).toMatchInlineSnapshot(); /* ... gets filled automatically by jest ... */});

It's typically better to make more specific assertions than to use snapshots. These kinds of tests include implementation details so they break easily, and teams can get desensitized to snapshot breakages. Selectively mocking some child components can help reduce the size of snapshots and keep them readable for the code review.