Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React snapshot testing - react-test-renderer vs. react-testing-library

Tags:

I am trying to do snapshot testing in my React app. I am already using react-testing-library for unit testing in general. However for snapshot testing I have seen different ways of doing it on the net, either using react-test-renderer or react-testing library. Here are 3 examples, what is the difference between them and what is preferred?

1. Using react-test-renderer

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

2. Using react-testing-library and asFragment()

test('renders correctly', () => {
  const { asFragment } = render(<NotFound />);
  expect(asFragment()).toMatchSnapshot();
});

3. Using react-testing-library and container

test('renders the component', () => {
  const container = render(<Component />)
  expect(container.firstChild).toMatchSnapshot()
})
like image 469
Naresh Avatar asked Feb 25 '21 05:02

Naresh


People also ask

Does React testing library use React test renderer?

The React Native Testing Library (RNTL) is a lightweight solution for testing React Native components. It provides light utility functions on top of react-test-renderer , in a way that encourages better testing practices.

Does React testing library have snapshot?

Snapshot testing It works well with React components because when you render a component you can view the DOM output and create a “snapshot” at the time of run.

Should I use snapshot testing React?

Snapshot tests are useful when you want to make sure your UI does not change unexpectedly. A typical snapshot test case renders a UI component, takes a snapshot, then compares it to a reference snapshot file stored alongside the test.


1 Answers

After much experimentation, I settled on option 2 (react-testing-library with asFragment()) because it produces cleaner snapshots. Option 1 (react-test-renderer) generates output that contains component properties and other details that are not relevant.

like image 108
Naresh Avatar answered Sep 28 '22 11:09

Naresh