Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make testing-library's getByText() match a string including a non-breaking space ( )?

I'm trying to match a phone number string that includes a non-breaking space:

assert
   .dom(
      screen.getByText(
         [my text with a non-breaking space]
      ) as HTMLElement
   )
.exists();

However, it is returning this error:

Unable to find an element with the text: [my text with a non-breaking space]. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

How can I test this?

like image 541
Jim Hays Avatar asked Oct 14 '25 14:10

Jim Hays


1 Answers

The testing library automatically normalizes whitespace, so the non-breaking space gets converted to a regular space by default. See more about the default behavior at: https://testing-library.com/docs/queries/about/#normalization

To override this behavior and leave it as a non-breaking space (so that it will match your assert), set the collapseWhitespace parameter to false.

This will look something like this:

assert
   .dom(
      screen.getByText(
         [my text with a non-breaking space], 
         { collapseWhitespace: false }
      ) as HTMLElement
   )
.exists();
like image 186
Jim Hays Avatar answered Oct 20 '25 07:10

Jim Hays



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!