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

5.8k Views Asked by At

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?

1

There are 1 best solutions below

0
On

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();