Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a an argument to getByText in react Testing Library?

Currently I'm doing this

getByText(/SomText/i);

But i want to make a function and pass some text as an argument. I tried doing it like this

let x = "/SomeText/i";
getByText(x);

or

getByText(`/${x}/i`);

But none of the options work.

like image 555
Dhaivat Parikh Avatar asked Nov 10 '19 22:11

Dhaivat Parikh


People also ask

How will you test span in React testing library?

import { screen } from "@testing-library/react"; ... // get HTML DOM element const spanElement = await screen. queryByTestId('test-span'); // OR // const spanElement = await screen. querySelector('test-span'); // get value from HTML DOM element const spanElementValue = spanElement. getAttribute('value'); ...


2 Answers

If you have

const x = "Some string"

To test for x using regex,

getByText(new RegExp(x, "i"))
like image 127
yishus Avatar answered Sep 22 '22 07:09

yishus


Perhaps you are looking for passing exact: false?

// Match a substring of Hello World
getByText(container, 'llo Worl', { exact: false }) // substring match

You can also pass your own matching custom function.

getByText(container, (content, element) => content.startsWith('Hello'))

https://testing-library.com/docs/dom-testing-library/cheatsheet#text-match-options

like image 27
Brady Clifford Avatar answered Sep 23 '22 07:09

Brady Clifford