Ir para o conteúdo principal

Guia de Referência

[Tradução Beta Não Oficial]

Esta página foi traduzida por PageTurner AI (beta). Não é oficialmente endossada pelo projeto. Encontrou um erro? Reportar problema →

Um guia rápido para todas as funções exportadas na DOM Testing Library

Consultas (Queries)

Veja Qual consulta devo usar?

No Match1 Match1+ MatchAwait?
getBythrowreturnthrowNo
findBythrowreturnthrowYes
queryBynullreturnthrowNo
getAllBythrowarrayarrayNo
findAllBythrowarrayarrayYes
queryAllBy[]arrayarrayNo
  • 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

Veja API Assíncrona. Lembre-se de usar await ou .then() com os resultados de funções assíncronas nos seus testes!

  • 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

Depreciado desde a v7.0.0:

  • wait (Promise) repete a função internamente até que pare de lançar erros ou atinja o timeout
  • waitForElement (Promise) repete a função até que ela retorne um elemento ou um array de elementos. As consultas findBy e findAllBy são assíncronas e repetem até que a consulta retorne com sucesso, ou quando o tempo da consulta expira; elas envolvem waitForElement
  • waitForDomChange (Promise) repete a função cada vez que o DOM é alterado

Eventos

Veja Considerações sobre fireEvent, API de Eventos

Outros

Veja Consultando Dentro de Elementos, API de Configuração

  • 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'})

Opções de Correspondência de Texto

Dado o seguinte HTML:

<div>Hello World</div>

Encontrará a div:

// Matching a string:
getByText(container, 'Hello World') // full string match
getByText(container, 'llo Worl', {exact: false}) // substring match
getByText(container, 'hello world', {exact: false}) // ignore case

// Matching a regex:
getByText(container, /World/) // substring match
getByText(container, /world/i) // substring match, ignore case
getByText(container, /^hello world$/i) // full string match, ignore case
getByText(container, /Hello W?oRlD/i) // advanced regex

// Matching with a custom function:
getByText(container, (content, element) => content.startsWith('Hello'))

Dado um botão que atualiza a página após algum tempo:

test('loads items eventually', async () => {
// Click button
fireEvent.click(getByText(node, 'Load'))

// Wait for page to update with query text
const items = await findAllByText(node, /Item #[0-9]: /)
expect(items).toHaveLength(10)
})