6. Use Snapshot Testing

To test the rendered output of a specific component we can use snapshot testing. We need to install the react-test-render package first:

yarn add react-test-renderer --dev

Then we will create a file called FaqItem.test.js. Here we will render the component and assert the markup.

 1import React from "react";
 2import renderer from "react-test-renderer";
 4import FaqItem from "./FaqItem";
 6describe("FaqItem", () => {
 7  it("renders a FAQ item", () => {
 8    const component = renderer.create(
 9      <FaqItem
10        question="What is the answer to life the universe and everything?"
11        answer="42"
12      />
13    );
14    const json = component.toJSON();
15    expect(json).toMatchSnapshot();
16  });

To run our tests we will run the command:

yarn test

This will output our test results:

PASS  src/components/FaqItem.test.js
PASS  src/App.test.js

Test Suites: 2 passed, 2 total
Tests:       2 passed, 2 total
Snapshots:   1 passed, 1 total
Time:        1.491s
Ran all test suites related to changed files.