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

Consultas (Queries)

Diferença em relação à DOM Testing Library

As consultas retornadas pelo render na Vue Testing Library são as mesmas da DOM Testing Library. Porém, o primeiro argumento está vinculado ao documento, então em vez de getByText(node, 'text'), você escreve getByText('text').

Variantes de busca

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

Tipos de busca

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" />

Você pode escrever qualquer combinação de variantes de busca e tipos de busca.

Um exemplo

getByLabelText('Username') irá procurar por um elemento <label> que contenha a string "Username" e retornará o input associado. Caso não encontre nenhum, ou encontre mais de um, lançará um erro.

queryAllByRole('nav') irá procurar de forma síncrona por todos os elementos com atributo role="nav" e retornará um array com os resultados (ou um array vazio se nenhum resultado for encontrado).

Para mais informações, consulte Qual consulta devo usar?.

Utilitários assíncronos

  • waitFor (Promise) repete a função até que ela pare de lançar erros ou o tempo limite seja atingido.

  • waitForElement (Promise) repete uma função ou array de funções e retorna o resultado.

  • As consultas findBy e findAllBy são assíncronas e repetem até que ocorra um tempo limite ou a consulta retorne com sucesso; elas envolvem o waitForElement.

Para mais informações, consulte API assíncrona da DOM Testing Library.

Lembre-se de usar await ou .then() no resultado de funções assíncronas em seus testes!

Disparando eventos

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

  • fireEvent.* auxiliares para tipos de evento padrão

Para mais informações, consulte API de eventos

Diferença em relação à DOM Testing Library

Os eventos retornados pela Vue Testing Library são todos assíncronos, então você deve usar await ou then() no resultado.

A VTL também expõe o evento fireEvent.update(node, value) para lidar com v-model. Veja a API para mais detalhes.

Outros

  • within(node) recebe um nó e retorna um objeto com todas as consultas vinculadas a ele: within(getByTestId("global-header")).getByText("hello").

  • configure(config) altera opções globais: configure({testIdAttribute: 'my-test-id'}).

Para mais informações, consulte Consultando dentro de elementos e API de configuração.

Opções de Correspondência de Texto

Dado o seguinte HTML:

<div>Hello World</div>

Todos esses matchers encontrarão o 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'))