vitest/docs/guide/test-context.md
Joe Zimmerman 3ecc91ef98
docs: a few spelling/grammar fixes (#1701)
* Fix typos and enhance grammar.

* Merge branch 'main'

* Apply suggestions from code review

Co-authored-by: Anjorin Damilare <damilareanjorin1@gmail.com>

Co-authored-by: Vladimir <sleuths.slews0s@icloud.com>
Co-authored-by: Anjorin Damilare <damilareanjorin1@gmail.com>
2022-07-24 09:47:29 +03:00

1.1 KiB

title
Test Context | Guide

Test Context

Inspired by Playwright Fixtures, Vitest's test context allows you to define utils, states, and fixtures that can be used in your tests.

Usage

The first argument for each test callback is a test context.

import { it } from 'vitest'

it('should work', (ctx) => {
  // prints name of the test
  console.log(ctx.meta.name)
})

Built-in Test Context

context.meta

A readonly object containing metadata about the test.

context.expect

The expect API bound to the current test.

Extend Test Context

The contexts are different for each test. You can access and extend them within the beforeEach and afterEach hooks.

import { beforeEach, it } from 'vitest'

beforeEach(async (context) => {
  // extend context
  context.foo = 'bar'
})

it('should work', ({ foo }) => {
  console.log(foo) // 'bar'
})

TypeScript

To provide types for your custom context properties, you can aggregate the TestContext type by adding

declare module 'vitest' {
  export interface TestContext {
    foo?: string
  }
}