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.
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'); ...
If you have
const x = "Some string"
To test for x
using regex,
getByText(new RegExp(x, "i"))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With