Guia de Referência
Esta página foi traduzida por PageTurner AI (beta). Não é oficialmente endossada pelo projeto. Encontrou um erro? Reportar problema →
Obtenha o guia de referência para impressão
Um guia rápido de todas as funções exportadas no React Testing Library
- render
const {/* */} = render(Component)retorna:- função
unmountpara desmontar o componente containerreferência ao nó DOM onde o componente está montado- todas as consultas do
DOM Testing Library, vinculadas ao documento, então não é necessário passar um nó como primeiro argumento (geralmente, você pode usar a importaçãoscreenem vez disso)
- função
import {render, fireEvent, screen} from '@testing-library/react'
test('loads items eventually', async () => {
render(<Page />)
// Click button
fireEvent.click(screen.getByText('Load'))
// Wait for page to update with query text
const items = await screen.findAllByText(/Item #[0-9]: /)
expect(items).toHaveLength(10)
})
Consultas (Queries)
Diferença em relação ao DOM Testing Library
As consultas retornadas pelo
rendernoReact Testing Librarysão as mesmas doDOM Testing Library, exceto que o primeiro argumento está vinculado ao documento. Portanto, em vez degetByText(node, 'text'), você usagetByText('text')
| No Match | 1 Match | 1+ Match | Await? | |
|---|---|---|---|---|
| getBy | throw | return | throw | No |
| findBy | throw | return | throw | Yes |
| queryBy | null | return | throw | No |
| getAllBy | throw | array | array | No |
| findAllBy | throw | array | array | Yes |
| queryAllBy | [] | array | array | No |
ByLabelText busca por rótulo ou conteúdo de texto aria-label
- getByLabelText
- queryByLabelText
- getAllByLabelText
- queryAllByLabelText
- findByLabelText
- findAllByLabelText
ByPlaceholderText busca pelo valor do placeholder de inputs
- getByPlaceholderText
- queryByPlaceholderText
- getAllByPlaceholderText
- queryAllByPlaceholderText
- findByPlaceholderText
- findAllByPlaceholderText
ByText busca por conteúdo de texto do elemento
- getByText
- queryByText
- getAllByText
- queryAllByText
- findByText
- findAllByText
ByDisplayValue busca pelo valor atual de elementos de formulário
- getByDisplayValue
- queryByDisplayValue
- getAllByDisplayValue
- queryAllByDisplayValue
- findByDisplayValue
- findAllByDisplayValue
ByAltText busca pelo atributo alt de imagens
- getByAltText
- queryByAltText
- getAllByAltText
- queryAllByAltText
- findByAltText
- findAllByAltText
ByTitle busca por atributo title ou tag title em SVGs
- getByTitle
- queryByTitle
- getAllByTitle
- queryAllByTitle
- findByTitle
- findAllByTitle
ByRole busca por função ARIA
- getByRole
- queryByRole
- getAllByRole
- queryAllByRole
- findByRole
- findAllByRole
ByTestId busca por atributo data-testid
- getByTestId
- queryByTestId
- getAllByTestId
- queryAllByTestId
- findByTestId
- findAllByTestId
Assíncrono
A API Assíncrona do dom-testing-library é reexportada pelo React Testing Library.
waitFor (Promise) repete a função internamente até que pare de lançar erros ou atinja o timeout
waitForElementToBeRemoved (Promise) repete a função até que ela não retorne mais um nó DOM
Eventos
Veja API de Eventos
fireEvent dispara evento DOM:
fireEvent(node, event)fireEvent.* helpers para tipos de evento padrão
- click
fireEvent.click(node) - Veja todos os eventos suportados
- click
act wrapper em torno do react act; O React Testing Library já envolve render e fireEvent em
act, então na maioria dos casos não é necessário usá-lo manualmente
Outros
Veja Consultando Dentro de Elementos, API de Configuração, Limpeza,
within recebe um nó e retorna um objeto com todas as consultas vinculadas ao nó (usado para retornar as consultas do método render do
React Testing Library):within(node).getByText("hello")configure altera opções globais:
configure({testIdAttribute: 'my-data-test-id'})cleanup limpa o DOM (use com
afterEachpara redefinir o DOM entre os testes)
Opções de Correspondência de Texto
Dado o seguinte HTML:
<div>Hello World</div>
Encontrará a div:
// Matching a string:
getByText('Hello World') // full string match
getByText('llo Worl', {exact: false}) // substring match
getByText('hello world', {exact: false}) // ignore case
// Matching a regex:
getByText(/World/) // substring match
getByText(/world/i) // substring match, ignore case
getByText(/^hello world$/i) // full string match, ignore case
getByText(/Hello W?oRlD/i) // advanced regex
// Matching with a custom function:
getByText((content, element) => content.startsWith('Hello'))