14

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 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks @Naresh. I came with the exact same question; (somehow) related post: dev.to/manuartero/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.