简体   繁体   English

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

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

I have an element that has a combination of static and dynamic text all on the same line.我有一个元素,它在同一行上结合了 static 和动态文本。

When testing for this line of text by a substring including some of the static and dynamic text, it fails, showing the output being split onto multiple lines with the splits before and after the dynamic section.当通过 substring 测试这行文本时,包括一些 static 和动态文本,它失败了,显示 output 被拆分为多行,并在动态之前和之后拆分。

What is going on?到底是怎么回事? Why can't I test it in the way I am expecting?为什么我不能以我期望的方式测试它? How would I test this properly?我将如何正确测试这个?

Code.jsx代码.jsx

const dynamicText = 'all be on one line';

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

Code.spec.js代码.spec.js

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

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

Test output测试 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>

I figured out a way in which this can be done easily.我想出了一种可以轻松完成的方法。

In my code I was trying to match a substring of the full string as I was merely interested in checking that the dynamic part rendered properly.在我的代码中,我试图匹配完整字符串的 substring,因为我只是对检查动态部分是否正确呈现感兴趣。 Specifying the string I am looking for within quotes (single or double) seems to make RTL look at this like a definitive string.在引号(单引号或双引号)中指定我要查找的字符串似乎使 RTL 看起来像一个确定的字符串。

Instead, I changed the single quotes to make it more of a regex style, so changing 'should all be on one line' to /should all be on one line/ .相反,我更改了单引号以使其更像正则表达式样式,因此将'should all be on one line'更改为/should all be on one line/

The test now passes:)现在测试通过了:)

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

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