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()
})
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With