Back to Testing Library

ByText

docs/queries/bytext.mdx

latest2.3 KB
Original Source

import Tabs from '@theme/Tabs' import TabItem from '@theme/TabItem'

getByText, queryByText, getAllByText, queryAllByText, findByText, findAllByText

API

typescript
getByText(
  // If you're using `screen`, then skip the container argument:
  container: HTMLElement,
  text: TextMatch,
  options?: {
    selector?: string = '*',
    exact?: boolean = true,
    ignore?: string|boolean = 'script, style',
    normalizer?: NormalizerFn,
  }): HTMLElement

This will search for all elements that have a text node with textContent matching the given TextMatch.

html
<a href="/about">About ℹ️</a>

<Tabs defaultValue="native" values={[ { label: 'Native', value: 'native', }, { label: 'React', value: 'react', }, { label: 'Angular', value: 'angular', }, { label: 'Cypress', value: 'cypress', }, ] }> <TabItem value="native">

js
import {screen} from '@testing-library/dom'

const aboutAnchorNode = screen.getByText(/about/i)
</TabItem> <TabItem value="react">
jsx
import {render, screen} from '@testing-library/react'

render(<MyComponent />)
const aboutAnchorNode = screen.getByText(/about/i)
</TabItem> <TabItem value="angular">
ts
import {render, screen} from '@testing-library/angular'

await render(MyComponent)
const aboutAnchorNode = screen.getByText(/about/i)
</TabItem> <TabItem value="cypress">
js
cy.findByText(/about/i).should('exist')
</TabItem> </Tabs>

It also works with inputs whose type attribute is either submit or button:

js
<input type="submit" value="Send data" />

Options

TextMatch options, plus the following:

selector

Note

See getByLabelText for more details on how and when to use the selector option

ignore

The ignore option accepts a query selector. If the node.matches returns true for that selector, the node will be ignored. This defaults to 'script, style' because generally you don't want to select these tags, but if your content is in an inline script file, then the script tag could be returned.

If you'd rather disable this behavior, set ignore to false.