Saltar al contenido principal

Hoja de referencia rápida

[Traducción Beta No Oficial]

Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →

Obtén la hoja de referencia rápida imprimible

Una guía breve de todas las funciones exportadas en React Testing Library

  • render const {/* */} = render(Component) devuelve:
    • función unmount para desmontar el componente
    • referencia container al nodo DOM donde está montado el componente
    • todas las consultas de DOM Testing Library, vinculadas al documento por lo que no es necesario pasar un nodo como primer argumento (normalmente, puedes usar la importación screen en su lugar)
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

Diferencia con DOM Testing Library

Las consultas devueltas por render en React Testing Library son las mismas que en DOM Testing Library, excepto que tienen el primer argumento vinculado al documento, por lo que en lugar de getByText(node, 'text') se usa getByText('text')

Ver ¿Qué consulta debería usar?

No Match1 Match1+ MatchAwait?
getBythrowreturnthrowNo
findBythrowreturnthrowYes
queryBynullreturnthrowNo
getAllBythrowarrayarrayNo
findAllBythrowarrayarrayYes
queryAllBy[]arrayarrayNo
  • ByLabelText buscar por texto de etiqueta o aria-label

    • getByLabelText
    • queryByLabelText
    • getAllByLabelText
    • queryAllByLabelText
    • findByLabelText
    • findAllByLabelText
  • ByPlaceholderText buscar por valor de placeholder en inputs

    • getByPlaceholderText
    • queryByPlaceholderText
    • getAllByPlaceholderText
    • queryAllByPlaceholderText
    • findByPlaceholderText
    • findAllByPlaceholderText
  • ByText buscar por contenido textual de elementos

    • getByText
    • queryByText
    • getAllByText
    • queryAllByText
    • findByText
    • findAllByText
  • ByDisplayValue buscar por valor actual de elementos de formulario

    • getByDisplayValue
    • queryByDisplayValue
    • getAllByDisplayValue
    • queryAllByDisplayValue
    • findByDisplayValue
    • findAllByDisplayValue
  • ByAltText buscar por atributo alt de imágenes

    • getByAltText
    • queryByAltText
    • getAllByAltText
    • queryAllByAltText
    • findByAltText
    • findAllByAltText
  • ByTitle buscar por atributo title o etiqueta title en SVG

    • getByTitle
    • queryByTitle
    • getAllByTitle
    • queryAllByTitle
    • findByTitle
    • findAllByTitle
  • ByRole buscar por rol ARIA

    • getByRole
    • queryByRole
    • getAllByRole
    • queryAllByRole
    • findByRole
    • findAllByRole
  • ByTestId buscar por atributo data-testid

    • getByTestId
    • queryByTestId
    • getAllByTestId
    • queryAllByTestId
    • findByTestId
    • findAllByTestId

Asincronía

La API Asíncrona de dom-testing-library se reexporta desde React Testing Library.

  • waitFor (Promise) reintenta la función hasta que deje de lanzar errores o se agote el tiempo

  • waitForElementToBeRemoved (Promise) reintenta hasta que la función ya no devuelva un nodo DOM

Eventos

Ver API de Eventos

  • fireEvent dispara eventos DOM: fireEvent(node, event)

  • fireEvent.* ayudantes para tipos de eventos predeterminados

  • act envoltorio de react act; React Testing Library ya envuelve render y fireEvent en una llamada a act, por lo que en la mayoría de casos no será necesario usarlo manualmente

Otros

Ver Consultar dentro de elementos, API de Configuración, Limpieza,

  • within toma un nodo y devuelve un objeto con todas las consultas vinculadas al nodo (usado para devolver las consultas del método render de React Testing Library): within(node).getByText("hello")

  • configure modifica opciones globales: configure({testIdAttribute: 'my-data-test-id'})

  • cleanup limpia el DOM (usar con afterEach para reiniciar DOM entre pruebas)

Opciones de coincidencia de texto

Dado el siguiente HTML:

<div>Hello World</div>

Encontrará el 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'))

Obtén la hoja de referencia rápida imprimible