Show List

Snapshot testing

Snapshot testing is a technique where you capture the output of a component and save it as a "snapshot." On subsequent test runs, the output is compared against the saved snapshot to ensure that it hasn't changed unexpectedly.

Let's write a test case for snapshot testing using Jest and React Testing Library for a simple component called HelloWorld.


// HelloWorld.js import React from 'react'; const HelloWorld = () => { return ( <div> <h1>Hello, world!</h1> <p>This is a simple React component.</p> </div> ); }; export default HelloWorld;

Now, let's write a test case for snapshot testing.


// HelloWorld.test.js import React from 'react'; import { render } from '@testing-library/react'; import HelloWorld from './HelloWorld'; test('renders correctly', () => { const { container } = render(<HelloWorld />); expect(container).toMatchSnapshot(); });

In this test case:

  1. We render the HelloWorld component using render from React Testing Library.
  2. We use Jest's toMatchSnapshot matcher to capture the rendered output of the component and compare it against the saved snapshot.

When you run this test for the first time, Jest will generate a snapshot file (usually with a .snap extension) containing the rendered output of the component. On subsequent test runs, Jest will compare the current output with the saved snapshot. If there are differences, Jest will prompt you to review and potentially update the snapshot.

It's important to note that snapshot testing is not a replacement for unit testing. It's mainly useful for capturing the visual representation of your components and detecting unexpected changes in their output.

Remember to use snapshot testing judiciously and update snapshots when intentional changes are made to the component's output.


    Leave a Comment


  • captcha text