vitest/docs/guide/browser/retry-ability.md
Joaquín Sánchez 50130bdb59
docs: split browser page (#5988)
Co-authored-by: Vladimir <sleuths.slews0s@icloud.com>
2024-07-01 13:51:59 +02:00

38 lines
1.4 KiB
Markdown

---
title: Retry-ability | Browser Mode
---
# Retry-ability
Tests in the browser might fail inconsistently due to their asynchronous nature. Because of this, it is important to have a way to guarantee that assertions succeed even if the condition is delayed (by a timeout, network request, or animation, for example). For this purpose, Vitest provides retriable assertions out of the box via the [`expect.poll`](/api/expect#poll) and `expect.element` APIs:
```ts
import { expect, test } from 'vitest'
import { screen } from '@testing-library/dom'
test('error banner is rendered', async () => {
triggerError()
// @testing-library provides queries with built-in retry-ability
// It will try to find the banner until it's rendered
const banner = await screen.findByRole('alert', {
name: /error/i,
})
// Vitest provides `expect.element` with built-in retry-ability
// It will check `element.textContent` until it's equal to "Error!"
await expect.element(banner).toHaveTextContent('Error!')
})
```
::: tip
`expect.element` is a shorthand for `expect.poll(() => element)` and works in exactly the same way.
`toHaveTextContent` and all other [`@testing-library/jest-dom`](https://github.com/testing-library/jest-dom) assertions are still available on a regular `expect` without a built-in retry-ability mechanism:
```ts
// will fail immediately if .textContent is not `'Error!'`
expect(banner).toHaveTextContent('Error!')
```
:::