getByText 用于通过动态生成的字符串将文本拆分为单独的行

phy*_*boy 6 javascript testing unit-testing reactjs react-testing-library

我有一个元素,其中静态和动态文本的组合都在同一行上。

当通过包含一些静态和动态文本的子字符串测试此行文本时,它失败,显示输出被分割成多行,并且在动态部分之前和之后进行分割。

到底是怎么回事?为什么我不能按照我期望的方式测试它?我该如何正确测试这个?

代码.jsx

const dynamicText = 'all be on one line';

return <div>This should {dynamicText} like I expect.</div>
Run Code Online (Sandbox Code Playgroud)

代码.spec.js

it('Should have dynamic text on one line', () => {
    const {getByText} = render(<Code />);

    expect(getByText('should all be on one line ')).toBeTruthy();
});
Run Code Online (Sandbox Code Playgroud)

测试输出

Unable to find an element with the text: ... 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.

...


<div>
   This should 
   all be on one line
    like I expect
</div>

Run Code Online (Sandbox Code Playgroud)

phy*_*boy 8

我找到了一种可以轻松完成此操作的方法。

在我的代码中,我试图匹配完整字符串的子字符串,因为我只想检查动态部分是否正确呈现。在引号(单引号或双引号)内指定我要查找的字符串似乎使 RTL 将其视为确定的字符串。

相反,我更改了单引号以使其更像正则表达式样式,因此更改'should all be on one line'/should all be on one line/.

现在测试通过了:)