getByTestId, queryByTestId, getAllByTestId, queryAllByTestId, findByTestId, findAllByTestId
API
getByTestId(
// If you're using `screen`, then skip the container argument:
container: HTMLElement,
text: TextMatch,
options?: {
exact?: boolean = true,
normalizer?: NormalizerFn,
}): HTMLElement
container.querySelector([data-testid="${yourId}"]
)的快捷方式(并且它还可以接受TextMatch)。
// HTML
import {screen} from '@testing-library/dom'
const element = screen.getByTestId('custom-element')
// React
import {render, screen} from '@testing-library/react'
render(<MyComponent />)
const element = screen.getByTestId('custom-element')
根据指导原则的精神,建议仅在其他查询对您的情况不起作用时才使用此属性。使用 data-testid 属性不会反映您的软件如何被使用,因此应尽可能避免使用。不过,与基于 DOM 结构或 CSS 类名的样式查询相比,使用 data-testid 更好。您可以从博客文章“使您的 UI 测试具有抗变性”中了解更多有关 data-testid 的信息。
Options
覆盖 data-testid
DOM 测试库中的 ...ByTestId 函数默认使用 data-testid 属性,这是遵循 React Native Web 的先例,后者使用 testID 属性在元素上发布 data-testid 属性,我们建议您在可能的情况下采用该属性。但是,如果您已经有一个现有的代码库,它使用不同的属性来实现此目的,您可以通过 configure({testIdAttribute: 'data-my-test-attribute'}) 覆盖此值。