コンテンツにスキップ

テストコンテキスト

Playwrightフィクスチャに触発されたVitestのテストコンテキストでは、テストで使用できるユーティリティ、状態、およびフィクスチャを定義できます。

使用方法

各テストコールバックの最初の引数はテストコンテキストです。

ts
import {  } from 'vitest'

('should work', () => {
  // prints name of the test
  .(..)
})

組み込みテストコンテキスト

context.task

テストに関するメタデータを含む読み取り専用オブジェクト。

context.expect

現在のテストにバインドされたexpect API

ts
import {  } from 'vitest'

('math is easy', ({  }) => {
  (2 + 2).(4)
})

このAPIは、グローバルなexpectでは追跡できないため、スナップショットテストを並行して実行する場合に役立ちます。

ts
import {  } from 'vitest'

.('math is easy', ({  }) => {
  (2 + 2).()
})

.('math is hard', ({  }) => {
  (2 * 2).()
})

context.skip

後続のテスト実行をスキップし、テストをスキップ済みとしてマークします

ts
import { expect, it } from 'vitest'

it('math is hard', ({ skip }) => {
  skip()
  expect(2 + 2).toBe(5)
})

テストコンテキストの拡張

Vitestは、テストコンテキストを拡張するのに役立つ2つの異なる方法を提供します。

test.extend

警告

このAPIはVitest 0.32.3以降で使用可能です。

Playwrightと同様に、このメソッドを使用して、カスタムフィクスチャを使用して独自のtest APIを定義し、どこでも再利用できます。

たとえば、最初に2つのフィクスチャ`todos`と`archive`を使用して`myTest`を作成します。

ts
// my-test.ts
import { test } from 'vitest'

const todos = []
const archive = []

export const myTest = test.extend({
  todos: async ({}, use) => {
    // setup the fixture before each test function
    todos.push(1, 2, 3)

    // use the fixture value
    await use(todos)

    // cleanup the fixture after each test function
    todos.length = 0
  },
  archive
})

その後、インポートして使用できます。

ts
import { expect } from 'vitest'
import { myTest } from './my-test.js'

myTest('add items to todos', ({ todos }) => {
  expect(todos.length).toBe(3)

  todos.push(4)
  expect(todos.length).toBe(4)
})

myTest('move items from todos to archive', ({ todos, archive }) => {
  expect(todos.length).toBe(3)
  expect(archive.length).toBe(0)

  archive.push(todos.pop())
  expect(todos.length).toBe(2)
  expect(archive.length).toBe(1)
})

`myTest`を拡張することで、さらにフィクスチャを追加したり、既存のフィクスチャをオーバーライドしたりすることもできます。

ts
export const myTest2 = myTest.extend({
  settings: {
    // ...
  }
})

フィクスチャの初期化

Vitestランナーは、使用方法に基づいてフィクスチャをスマートに初期化し、テストコンテキストに挿入します。

ts
import { test } from 'vitest'

async function todosFn({ task }, use) {
  await use([1, 2, 3])
}

const myTest = test.extend({
  todos: todosFn,
  archive: []
})

// todosFn will not run
myTest('', () => {})
myTest('', ({ archive }) => {})

// todosFn will run
myTest('', ({ todos }) => {})

警告

フィクスチャで`test.extend()`を使用する場合は、フィクスチャ関数とテスト関数の両方で、オブジェクトの分割代入パターン`{ todos }`を使用してコンテキストにアクセスする必要があります。

自動フィクスチャ

警告

この機能はVitest 1.3.0以降で使用可能です。

Vitestは、フィクスチャにタプル構文もサポートしており、各フィクスチャのオプションを渡すことができます。たとえば、テストで使用されていない場合でも、フィクスチャを明示的に初期化するために使用できます。

ts
import { test as base } from 'vitest'

const test = base.extend({
  fixture: [
    async ({}, use) => {
      // this function will run
      setup()
      await use()
      teardown()
    },
    { auto: true } // Mark as an automatic fixture
  ],
})

test('', () => {})

TypeScript

すべてcのスタムコンテキストにフィクスチャ型を提供するには、フィクスチャ型をジェネリックとして渡します。

ts
interface MyFixtures {
  todos: number[]
  archive: number[]
}

const myTest = test.extend<MyFixtures>({
  todos: [],
  archive: []
})

myTest('', (context) => {
  expectTypeOf(context.todos).toEqualTypeOf<number[]>()
  expectTypeOf(context.archive).toEqualTypeOf<number[]>()
})

beforeEachafterEach

コンテキストはテストごとに異なります。`beforeEach`および`afterEach`フック内でアクセスして拡張できます。

ts
import { beforeEach, it } from 'vitest'

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

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

TypeScript

すべてcのスタムコンテキストにプロパティ型を提供するには、次を追加することで`TestContext`型を集約できます。

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

特定の`beforeEach`、`afterEach`、`it`、`test`フックにのみプロパティ型を提供する場合は、型をジェネリックとして渡すことができます。

ts
interface LocalTestContext {
  foo: string
}

beforeEach<LocalTestContext>(async (context) => {
  // typeof context is 'TestContext & LocalTestContext'
  context.foo = 'bar'
})

it<LocalTestContext>('should work', ({ foo }) => {
  // typeof foo is 'string'
  console.log(foo) // 'bar'
})

MITライセンスでリリースされています。