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 →

Una guía rápida de todas las funciones exportadas en DOM Testing Library

Consultas

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

Ver API Asíncrona. ¡Recuerda usar await o .then() con los resultados de funciones asíncronas en tus pruebas!

  • 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

Obsoleto desde v7.0.0:

  • wait (Promise): reintenta la función hasta que deje de lanzar errores o se agote el tiempo
  • waitForElement (Promise): reintenta la función hasta que devuelva un elemento o un array de elementos. Las consultas findBy y findAllBy son asíncronas y reintentan hasta que la consulta tiene éxito o se agota el tiempo; estas envuelven a waitForElement
  • waitForDomChange (Promise): reintenta la función cada vez que el DOM cambia

Eventos

Ver Consideraciones para fireEvent, API de Eventos

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

  • fireEvent.* ayudantes para tipos de eventos predeterminados

Otros

Ver Consultas dentro de elementos, API de Configuración

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

Opciones de coincidencia de texto

Dado el siguiente HTML:

<div>Hello World</div>

Encontrará el 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 un botón que actualiza la página después de un tiempo:

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