Skip to content

Assertion API

Vitest bundles the @testing-library/jest-dom library to provide a wide range of DOM assertions out of the box. For detailed documentation, you can read the jest-dom readme:

If you are using TypeScript or want to have correct type hints in expect, make sure you have either @vitest/browser/providers/playwright or @vitest/browser/providers/webdriverio referenced in your setup file or a config file depending on the provider you use. If you use the default preview provider, you can specify @vitest/browser/matchers instead.

ts
/// <reference types="@vitest/browser/matchers" />
ts
/// <reference types="@vitest/browser/providers/playwright" />
ts
/// <reference types="@vitest/browser/providers/webdriverio" />

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 and expect.element APIs:

ts
import { expect, test } from 'vitest'
import { page } from '@vitest/browser/context'

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 = page.getByRole('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 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!')

Released under the MIT License.