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

Currently I'm doing this

getByText(/SomeText/i);

But I want to make a function and pass some text as an argument by first storing it in a variable. I tried doing it like this:

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

or

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

But none of the options work.



Solution 1:[1]

If you have

const x = "Some string"

To test for x using regex,

getByText(new RegExp(x, "i"))

Solution 2:[2]

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

Solution 3:[3]

Welcome to SO!

I haven't tested this, but it seems getByText needs a regular expression:

getByText(/SomText/i);

as an argument and not, as you put here, a string:

let x = "/SomeText/i";

Does your code work if you create a regex from your string, like this?

let x = new RegExp("/SomeText/i");

Solution 4:[4]

I think your issue is your trying to set a RegEx as though it's a string

// Doesn't need quotes
let x = /SomeText/i

getByText(x)

What you're asking getByText to find is literally /SomeText/i, which I imagine your document does not have in it

Solution 5:[5]

I had a similar scenario where I needed a variable:

    const x = 'some text';
    getByText(`${x}`);    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 yishus
Solution 2 Brady Clifford
Solution 3 wrdevos
Solution 4 Kieran101
Solution 5 Justin Connell