Skip to content
Advertisement

React Testing with Jest and useParams-hook, tried with MemoryRouter

How do I test a component which needs the parameter from react-router to work?

Carousel.js component

JavaScript

Carousel.test.js

JavaScript

The test works if I comment the line with useParams out and just declare const id = 1;.

Then I’ve tried to use MemoryRouter. Carousel.test.js v2

JavaScript

And the test failed with this output

JavaScript

It seems that it worked for one inner loop cycle, but when the outer loop runs the second iteration, 3.jpg from last iteration is somehow still there. How do I fix it?

Advertisement

Answer

The @testing-library/react render by default creates a div and append that div to the document.body. Since you’re rendering multiple times in one test, then it would only be apparent that the entire JSX render would be appended multiple times. If you don’t want this to happen, I suggest you perform a cleanup after each rendered loop.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement