getAllByRole 和 getByText 结合使用

huangapple go评论50阅读模式
英文:

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"})

huangapple
  • 本文由 发表于 2023年6月29日 21:15:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76581433.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定