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 Vue Testing Library.

Consultas

Diferencia con DOM Testing Library

Las consultas devueltas por render en Vue Testing Library son idénticas a las de DOM Testing Library. Sin embargo, tienen el primer argumento vinculado al documento, así que en lugar de getByText(node, 'text') se escribe getByText('text').

Variantes de búsqueda

Return if no matchReturn if 1 matchReturn if 1+ matchAwait?
getBy...throwreturnthrowNo
findBy...throwreturnthrowYes
queryBy...nullreturnthrowNo
getAllBy...throwarrayarrayNo
findAllBy...throwarrayarrayYes
queryAllBy...[]arrayarrayNo

Tipos de búsqueda

finds by...DOM example
...ByLabelTextlabel or aria-label content<label for="element" />
...ByPlaceholderTextinput placeholder value<input placeholder="name" />
...ByTextelement text content<p>Lorem ipsum</p>
...ByDisplayValueform element current valueCurrent value of input element
...ByAltTextimg alt attribute<img alt="movie poster" />
...ByTitletitle attribute or svg title tag<span title="Add" /> or <title />
...ByRoleARIA role<div role="dialog" />
...ByTestIddata-testid attribute<div data-testid="some-message" />

Puedes escribir cualquier combinación de Variantes de búsqueda y Tipos de búsqueda.

Un ejemplo

getByLabelText('Username') buscará un elemento <label> que contenga el texto "Usuario", y devolverá el input asociado. Si no encuentra ninguno, o encuentra más de uno, lanzará un error.

queryAllByRole('nav') buscará síncronamente todos los elementos con un atributo role="nav", y devolverá un array con los resultados (o un array vacío si no se encontraron resultados).

Para más información, consulta ¿Qué consulta debería usar?.

Utilidades asíncronas

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

  • waitForElement (Promise) reintenta una función o array de funciones y devuelve el resultado.

  • Las consultas findBy y findAllBy son asíncronas y reintentan hasta que ocurra un timeout o la consulta devuelva éxito; encapsulan waitForElement.

Para más información, consulta API Asíncrona de DOM Testing Library.

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

Disparo de eventos

  • fireEvent() dispara un evento DOM: fireEvent(node, event)

  • fireEvent.* ayudantes para tipos de eventos predeterminados

Para más información, consulta API de Eventos

Diferencia con DOM Testing Library

Los eventos devueltos por Vue Testing Library son todos asíncronos, por lo que debes usar await o then() con el resultado.

VTL también expone el evento fireEvent.update(node, value) para manejar v-model. Consulta la API para más detalles.

Otros

  • within(node) toma un nodo y devuelve un objeto con todas las consultas vinculadas a él: within(getByTestId("global-header")).getByText("hello").

  • configure(config) cambia opciones globales: configure({testIdAttribute: 'my-test-id'}).

Para más información, consulta Consultar dentro de elementos y API de Configuración.

Opciones de coincidencia de texto

Dado el siguiente HTML:

<div>Hello World</div>

Todos estos comparadores encontrarán el elemento:

// 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'))