Write a snapshot test using Jest:?
Short answer: import { render } from '@testing-library/react'; import MyComponent from './MyComponent'; test('matches snapshot', () => { const { asFragment } = render(<MyComponent />); expect(asFragment()).toMatchSnapshot(); }); asFragment() captures the rendered output as a DOM snapshot.
Explain a bit more
toMatchSnapshot() compares the output to a previously saved snapshot. The first time the test is run, it saves the output to a snapshot file. On subsequent runs, it compares the output to the saved snapshot. If there are any changes, the test will fail. Advanced React Concepts
Real-world example (ShopNest)
ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state.
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png