如何使测试库的 getByText() 匹配包含不间断空格 ( ) 的字符串?

Jim*_*ays 4 non-breaking-characters testing-library

我正在尝试匹配包含不间断空格的电话号码字符串:

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

但是,它返回此错误:

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.

我该如何测试这个?

Jim*_*ays 5

测试库会自动标准化空格,因此默认情况下不间断空格会转换为常规空格。有关默认行为的更多信息,请访问: https://testing-library.com/docs/queries/about/#normalization

要覆盖此行为并将其保留为不间断空格(以便它与您的 匹配assert),请将collapseWhitespace参数设置为false

这看起来像这样:

assert
   .dom(
      screen.getByText(
         [my text with a non-breaking space], 
         { collapseWhitespace: false }
      ) as HTMLElement
   )
.exists();
Run Code Online (Sandbox Code Playgroud)