繁体   English   中英

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

[英]getByText for text split onto separate lines by dynamically generated string

我有一个元素,它在同一行上结合了 static 和动态文本。

当通过 substring 测试这行文本时,包括一些 static 和动态文本,它失败了,显示 output 被拆分为多行,并在动态之前和之后拆分。

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

代码.jsx

const dynamicText = 'all be on one line';

return <div>This should {dynamicText} like I expect.</div>

代码.spec.js

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

    expect(getByText('should all be on one line ')).toBeTruthy();
});

测试 output

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>

我想出了一种可以轻松完成的方法。

在我的代码中,我试图匹配完整字符串的 substring,因为我只是对检查动态部分是否正确呈现感兴趣。 在引号(单引号或双引号)中指定我要查找的字符串似乎使 RTL 看起来像一个确定的字符串。

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

现在测试通过了:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM