Sun Jan 22 2023

[SOLVED] React Testing Library snapshots failing due to dynamically generated IDs

A solution to prevent RTL snapshots from failing every time your tests run due to dynamically generated IDs

Recently a good friend of mine had a situation where porting some snapshot tests to React Testing Library snapshots made the tests fail as the HTML rendered from the component had different Ids every single time the test ran. See below example

Screenshot 2023-01-22 at 12.32.19

As you can see the swiper wrapper Id is dynamically generated and would fail the test every single time.

Here is the fix that helped overcome this

1test("Slider component should match snapshot", async () => {
2 const { asFragment } = await render(<Slider />);
3 const attributeToRemove = document.body.querySelector(
4 'div [id^="swiper-wrapper"]'
5 );
6 attributeToRemove?.removeAttribute("id");
7 expect(asFragment()).toMatchSnapshot();

What's happening here is that we look for divs with the problematic id and then remove it from the rendered component before making the toMatchSnapshot() assertion.

Shout out to Grzegorz Rogozik for teaching something new!

Let me know if the above helped you or if you have a better method of solving the same!