Using React Testing Library to test if component contains an instance of another component

Isaac Kasongoyo
3 min readJun 6, 2020

I love RTL because of it’s core principle that prohibit testing of the implementation details of the component. Before I was using enzyme and although it was easy and great testing library but it gives developer so much power to test implementation details of the component, something which can make tests more fragile and complicated for developer who struggles to achieve big testing coverage(Sorry, I don’t do this anymore).

Recenty when I was writing tests in my project, I encounted this problem which tempted me so much to test implementation details of my component and it actually made me to miss enzyme(just kiddin). The problem was I had parent component which renders two child components conditionally and that’s it. I wanted to write tests that can give me confidence which component get rendered based on the condition. Here are my component(not real components but just imaginary for demonstration purpose)

Component to test

Testing this kind of component with RTL without crossing its line brings a whole new challenge that’s fun and intimidating. I tried to google around and see if somebody else has ever faced similar problem and yes there were several links to stackoveflow and github and although they gave me idea but not a single link had a complete solution so I had to figure it out by myself, something which I did and it’s what I am gonna show you shortly. But among the existing solutions that I saw, one was to wrap the child components with another html tag that contain data-testid so that you can test the presence of the child components using those ids, something that I don’t like just modifying the component structure to make the component testable and another was about to inspect the child’s component implementation details and using RTL api to query against those details, something which make test fragile and subject to change whenever child component change — we never wanted this to happens with RTL. The last solution of which inspired mine was mocking of the child components, well I liked it and I felt like it’s one that confirm with RTL philosophy.

Solution

The best approach to test this kind of component is to mock the child components. Here are the tests for the parent component that I believe are clean and align with RTL core principle.

As you can see, I have mocked child components with simple div component that contain testid, this is absolute fine because at this point of time, what I care is to know if Auth component will render when prop authenticated is true or Public component when it’s false and nothing more. If you want to test how the real child component behave then you need to write separate tests for it.

That’s all for today and I’m open for the different thoughts if exist as I am still learning and hungry to improve my knowledge everyday.

--

--