Guia de Referência
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
rendernaVue Testing Librarysão as mesmas daDOM Testing Library. Porém, o primeiro argumento está vinculado ao documento, então em vez degetByText(node, 'text'), você escrevegetByText('text').
Variantes de busca
| Return if no match | Return if 1 match | Return if 1+ match | Await? | |
|---|---|---|---|---|
| getBy... | throw | return | throw | No |
| findBy... | throw | return | throw | Yes |
| queryBy... | null | return | throw | No |
| getAllBy... | throw | array | array | No |
| findAllBy... | throw | array | array | Yes |
| queryAllBy... | [] | array | array | No |
Tipos de busca
| finds by... | DOM example | |
|---|---|---|
| ...ByLabelText | label or aria-label content | <label for="element" /> |
| ...ByPlaceholderText | input placeholder value | <input placeholder="name" /> |
| ...ByText | element text content | <p>Lorem ipsum</p> |
| ...ByDisplayValue | form element current value | Current value of input element |
| ...ByAltText | img alt attribute | <img alt="movie poster" /> |
| ...ByTitle | title attribute or svg title tag | <span title="Add" /> or <title /> |
| ...ByRole | ARIA role | <div role="dialog" /> |
| ...ByTestId | data-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
findByefindAllBysão assíncronas e repetem até que ocorra um tempo limite ou a consulta retorne com sucesso; elas envolvem owaitForElement.
Para mais informações, consulte API assíncrona da DOM Testing Library.
Lembre-se de usar
awaitou.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
- click
fireEvent.click(node) - input
fireEvent.input(node, event) - Veja todos os eventos suportados
- click
Para mais informações, consulte API de eventos
Diferença em relação à DOM Testing Library
Os eventos retornados pela
Vue Testing Librarysão todos assíncronos, então você deve usarawaitouthen()no resultado.A VTL também expõe o evento
fireEvent.update(node, value)para lidar comv-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'))