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

5

31

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.

Wappes answered 10/11, 2019 at 22:32 Comment(0)
C
39

If you have

const x = "Some string"

To test for x using regex,

getByText(new RegExp(x, "i"))
Colin answered 14/4, 2020 at 7:52 Comment(1)
Or simply use the RegEx as a variable. const x = /Some string/i; getByText(x);Reliable
C
28

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

Cispadane answered 15/1, 2020 at 2:47 Comment(1)
I would say { exact: false } is the way to goThurber
R
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

Reliable answered 15/10, 2020 at 2:39 Comment(0)
E
3

Welcome to SO!

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

getByText(/SomeText/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");
Emelda answered 10/11, 2019 at 22:46 Comment(1)
Thanks for the help. But the solution doesn't work. I got the following error on console. Unable to find an element with the text: /\/SomeText\/i/.Wappes
P
1

I had a similar scenario where I needed a variable:

    const x = 'some text';
    getByText(`${x}`);    
Pillbox answered 13/2, 2022 at 19:36 Comment(1)
This is equivalent to getByText(x)Tangier

© 2022 - 2024 — McMap. All rights reserved.