英文:
getAllByRole and then getByText combined
问题
如何组合两个RTL屏幕方法?
我的页面上有几个H4标题,其中包含不同的文本。我希望a) 返回所有的h4标题,然后b) 根据文本返回一个特定的标题
- 我想保留它是一个标题的检查
- 我想保留标题是h4级别的检查
- 我想根据文本返回一个特定的h4标题
我不想直接使用getByText
来获取文本,而是要测试这两个部分:
const myHeading = screen.getAllByRole('heading', { level: 4 }).getByText("my heading text")
我知道可以编写一个find
函数来返回getAllByRole
返回的数组中的元素,以找到children
等于我的文本的元素。但这似乎有点混乱。是否有更简单的方法来组合两个RTL查询?
我尝试使用within
,但似乎within
是为页面部分而不是数组设计的,所以似乎不起作用。
英文:
How can I combine two RTL screen methods?
I have several H4s on my page, with different text inside. I wish to a) return back all h4s and then b) return a specific one by text
- I want to retain the check that it was a heading
- I want to retain the check that the heading was of level h4
- I want to pull back a specific h4 based on its text
I do not want to just dive right into the text using getByText
but test both parts:
const myHeading = screen.getAllByRole('heading', { level: 4 }).getByText("my heading text")
I know I can write a find
function to return the element inside the array returned by getAllByRole
to find the one with children
equalling my text. But it seems quite messy. Is there an easier way to combine two RTL queries?
I tried using within
however it seems within
is designed for a page section not an array, so it didn't seem to work.
答案1
得分: 1
我通常通过name
选项访问标题文本。也许这在你的情况下也适用?
即。
screen.getByRole("heading", {level: 4, name: "标题中的文本"})
英文:
I have usually accessed heading text through the name
option. Perhaps this could work in your case?
i.e.
screen.getByRole("heading", {level: 4, name: "text in the heading"})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论