Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parent node in react-testing-library

Tags:

The component that I have testing renders something this:

<div>Text<span>span text</span></div> 

As it turns out for testing the only reliable text that I have is the 'span text' but I want to get the 'Text' part of the <div>. Using Jest and react-testing-library I can

await screen.findByText(spanText) 

This returns an HTMLElement but it seems limited as I don't have any of the context around the element. For example HTML methods like parentNode and previousSibling return null or undefined. Ideally I would like to get the text content of the parent <div>. Any idea how I can do this with either Jest or react-testing-library?

like image 643
Kevin Burton Avatar asked Jul 07 '20 08:07

Kevin Burton


People also ask

What is container in React testing library?

container ​The containing DOM node of your rendered React Element (rendered using ReactDOM. render ). It's a div . This is a regular DOM node, so you can call container. querySelector etc. to inspect the children.

How do I use snapshot testing in React library?

When writing snapshot tests for a React component, you first need to have code in a working state. Then, generate a snapshot of its expected output given certain data. The snapshot tests are committed alongside the component. Jest, a testing framework, will compare the snapshot to the rendered output for the test.

What is a testing library?

The Testing Library family of libraries is a very light-weight solution for testing without all the implementation details. The main utilities it provides involve querying for nodes similarly to how users would find them. In this way, testing-library helps ensure your tests give you confidence in your UI code.


1 Answers

A good solution for this is the closest function. In description of closest function is written: Returns the first (starting at element) including ancestor that matches selectors, and null otherwise.

The solution would look like this:

screen.getByText("span text").closest("div") 
like image 153
Vitor Vicente Avatar answered Sep 20 '22 23:09

Vitor Vicente