5
votes

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()
})
1

1 Answers

4
votes

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.