Use Snapshot Testing

7. Use Snapshot Testing

To test the render output of a specific component, we can use snapshot testing.

First we will create a file called FaqItem.test.js. We will also delete the App.test.js file, because we have deleted all the initial content of App.js and tests refer to those. Here we will render the component and assert the markup.

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

To run our tests we will run the command:

yarn test

This will output our test results:

PASS  src/components/FaqItem.test.js

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