【问题标题】:how to select element with getByTestId that also has specific value with react-testing-library如何使用 getByTestId 选择元素,该元素也具有 react-testing-library 的特定值
【发布时间】:2021-09-29 09:01:19
【问题描述】:

在反应中,我从数组中映射出一些元素。例如

{options.map((option)=>{
  return <div data-testid="option">{option}</div>
})

我有多个测试要选择一个选项(不知道选项的 textContent 是什么),所以我使用data-testid="option" 并使用screenGetAllByTestId('option')[0] 选择第一个选项...

但是,有时我知道我想要什么特定的选项,我想getByTestId,但因为它们都共享相同的 data-testid 有点困难。

我正在尝试做的是类似于这个伪代码的东西:

screen.getAllByTestId('option').getByText("Apples")

这将获得所有选项,然后获得以 Apples 作为文本的特定选项

【问题讨论】:

标签: javascript typescript jestjs react-testing-library


【解决方案1】:

您也可以编写自定义匹配器函数,例如:

screen.getByText((content, element) => {
  return element.tagName.toLowerCase() === 'span' && content.startsWith('Hello')
})

From the docs

我认为在你的情况下,这意味着:

screen.getByText((content, element) => {
  return element.getAttribute('data-testid').toLowerCase() === 'option' && content === 'Apples'
})

更好的解决方案可能是在每组选项上附加清晰的文本标签,这样您的测试可以说:

// Find your menu / list header
const fruitsListHeader = screen.getByText('Fruits list');

// Find the menu or whatever it's in
// You can use plain old query selectors
const fruitsList = fruitsListHeader.closest('[role="menu"]')

// Look for your option in the right place, instead of 
// praying there are no duplicated options on the page.
const appleOption = within(fruitsList.closest('[role="menu"))
  .getByText('Apples');

within docs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-05
    • 2023-03-04
    • 2021-04-07
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 2021-04-10
    相关资源
    最近更新 更多