Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking text appears inside an element using react testing library

I'm writing some tests for a React app using Testing Library. I want to check that some text appears, but I need to check it appears in a particular place because I know it already appears somewhere else.

The Testing Library documentation for queries says that the getByText query takes a container parameter, which I guessed lets you search within that container. I tried doing this, with the container and text parameters in the order specified in the docs:

const container = getByTestId('my-test-id'); expect(getByText(container, 'some text')).toBeTruthy(); 

and I get an error: matcher.test is not a function.

If I put the params the other way round:

const container = getByTestId('my-test-id'); expect(getByText('some text', container)).toBeTruthy(); 

I get a different error: Found multiple elements with the text: some text

Which means it's not searching inside the specified container.

I think I'm not understanding how getByText works. What am I doing wrong?

like image 937
Hives Avatar asked Nov 21 '19 13:11

Hives


People also ask

What is within in React testing library?

within (an alias to getQueriesForElement ) takes a DOM element and binds it to the raw query functions, allowing them to be used without specifying a container. It is the recommended approach for libraries built on this API and is used under the hood in React Testing Library and Vue Testing Library.

How do you find the element by class name in React testing library?

To find elements by className in React testing library: Render a component and destructure the container object from the result. Use the getElementsByClassName() method on the container to find elements by class name.


2 Answers

Better to use within for this sort of things:

const { getByTestId } = render(<MyComponent />) const { getByText } = within(getByTestId('my-test-id')) expect(getByText('some text')).toBeInTheDocument() 
like image 86
Giorgio Polvara - Gpx Avatar answered Sep 21 '22 11:09

Giorgio Polvara - Gpx


Another way to do this

import {render, screen} from '@testing-library/react';  ...    render(<MyComponent />);   expect(screen.getByTestId('my-test-id')).toHaveTextContent('some text'); 

Note it is now recommended to use screen instead of the results of render.

(StackOverflow post the points to a KC Dobbs Article explaining why: react-testing-library - Screen vs Render queries)

like image 40
Seth McClaine Avatar answered Sep 23 '22 11:09

Seth McClaine