簡體   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