コンテンツへスキップ

テストAPIリファレンス

以下の型は、以下の型シグネチャで使用されます。

ts
type Awaitable<T> = T | PromiseLike<T>
type TestFunction = () => Awaitable<void>

interface TestOptions {
  /**
   * Will fail the test if it takes too long to execute
   */
  timeout?: number
  /**
   * Will retry the test specific number of times if it fails
   *
   * @default 0
   */
  retry?: number
  /**
   * Will repeat the same test several times even if it fails each time
   * If you have "retry" option and it fails, it will use every retry in each cycle
   * Useful for debugging random failings
   *
   * @default 0
   */
  repeats?: number
}

Vitest 1.3.0では、最後のパラメーターとしてオプションを使用することは非推奨となりました。この構文が削除される2.0.0までは、非推奨メッセージが表示されます。オプションを渡す必要がある場合は、test関数の2番目の引数を使用してください。

ts
import { test } from 'vitest'

test('flaky test', () => {}, { retry: 3 }) 
test('flaky test', { retry: 3 }, () => {}) 

テスト関数がPromiseを返す場合、ランナーは非同期の期待値を収集するために、Promiseが解決されるまで待機します。Promiseがリジェクトされた場合、テストは失敗します。

ヒント

Jestでは、TestFunction(done: DoneCallback) => voidの型にもなります。この形式を使用した場合、doneが呼び出されるまでテストは完了しません。async関数を使用しても同じことができます。 マイグレーションガイドのDone Callbackセクションを参照してください。

Vitest 1.3.0以降、ほとんどのオプションはドット構文とオブジェクト構文の両方をサポートしており、好みのスタイルを使用できます。

ts
import {  } from 'vitest'

.('skipped test', () => {
  // some logic that fails right now
})
ts
import {  } from 'vitest'

('skipped test', { : true }, () => {
  // some logic that fails right now
})

test

  • エイリアス: it

testは、関連する期待値のセットを定義します。テスト名と、テストする期待値を保持する関数を受け取ります。

オプションで、終了するまでの待機時間を指定するためにタイムアウト(ミリ秒単位)を指定できます。デフォルトは5秒で、testTimeoutでグローバルに設定できます。

ts
import { ,  } from 'vitest'

('should work as expected', () => {
  (.(4)).(2)
})

test.extend 0.32.3+

  • エイリアス: it.extend

test.extendを使用して、カスタムフィクスチャでテストコンテキストを拡張します。これにより、新しいtestが返され、拡張可能にもなるため、必要に応じてさらにフィクスチャを構成したり、既存のフィクスチャをオーバーライドしたりできます。詳細については、テストコンテキストの拡張を参照してください。

ts
import { expect, test } from 'vitest'

const todos = []
const archive = []

const myTest = test.extend({
  todos: async ({ task }, use) => {
    todos.push(1, 2, 3)
    await use(todos)
    todos.length = 0
  },
  archive
})

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

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

test.skip

  • エイリアス: it.skip

特定のテストの実行をスキップしたいが、何らかの理由でコードを削除したくない場合は、test.skipを使用して実行を回避できます。

ts
import { ,  } from 'vitest'

.('skipped test', () => {
  // Test skipped, no error
  .(.(4), 3)
})

テストのコンテキストで動的にskipを呼び出すことでテストをスキップすることもできます。

ts
import { ,  } from 'vitest'

('skipped test', () => {
  .()
  // Test skipped, no error
  .(.(4), 3)
})

test.skipIf

  • エイリアス: it.skipIf

環境が異なる状態で複数回テストを実行する必要がある場合があり、一部のテストは環境固有の場合があります。テストコードをifでラップする代わりに、条件がtrueの場合はいつでもtest.skipIfを使用してテストをスキップできます。

ts
import { ,  } from 'vitest'

const  = .. === 'development'

.()('prod only test', () => {
  // this test only runs in production
})

警告

Vitestを型チェッカーとして使用している場合は、この構文を使用できません。

test.runIf

  • エイリアス: it.runIf

test.skipIfの反対。

ts
import { ,  } from 'vitest'

const  = .. === 'development'

.()('dev only test', () => {
  // this test only runs in development
})

警告

Vitestを型チェッカーとして使用している場合は、この構文を使用できません。

test.only

  • エイリアス: it.only

特定のテストスイート内で特定のテストのみを実行するには、test.onlyを使用します。これはデバッグ時に役立ちます。

オプションで、終了するまでの待機時間を指定するためにタイムアウト(ミリ秒単位)を指定できます。デフォルトは5秒で、testTimeoutでグローバルに設定できます。

ts
import { ,  } from 'vitest'

.('test', () => {
  // Only this test (and others marked with only) are run
  .(.(4), 2)
})

出力が乱雑になるため、テストスイート全体から他のすべてのテストを無視して、特定のファイルでonlyテストを実行することが非常に便利な場合があります。

そのためには、対象のテストを含む特定のファイルでvitestを実行します。

# vitest interesting.test.ts

test.concurrent

  • エイリアス: it.concurrent

test.concurrentは、連続するテストを並行して実行するようにマークします。テスト名、収集するテストを含む非同期関数、およびオプションのタイムアウト(ミリ秒単位)を受け取ります。

ts
import { ,  } from 'vitest'

// The two tests marked with concurrent will be run in parallel
('suite', () => {
  ('serial test', async () => { /* ... */ })
  .('concurrent test 1', async () => { /* ... */ })
  .('concurrent test 2', async () => { /* ... */ })
})

test.skiptest.only、およびtest.todoは、並行テストで機能します。次のすべての組み合わせは有効です。

ts
test.concurrent(/* ... */)
test.skip.concurrent(/* ... */) // or test.concurrent.skip(/* ... */)
test.only.concurrent(/* ... */) // or test.concurrent.only(/* ... */)
test.todo.concurrent(/* ... */) // or test.concurrent.todo(/* ... */)

並行テストを実行する場合、スナップショットとアサーションは、正しいテストが検出されるように、ローカルのテストコンテキストからexpectを使用する必要があります。

ts
test.concurrent('test 1', async ({ expect }) => {
  expect(foo).toMatchSnapshot()
})
test.concurrent('test 2', async ({ expect }) => {
  expect(foo).toMatchSnapshot()
})

警告

Vitestを型チェッカーとして使用している場合は、この構文を使用できません。

test.sequential

  • エイリアス: it.sequential

test.sequentialは、テストをシーケンシャルとしてマークします。これは、describe.concurrent内または--sequence.concurrentコマンドオプションでテストを順番に実行したい場合に役立ちます。

ts
// with config option { sequence: { concurrent: true } }
('concurrent test 1', async () => { /* ... */ })
('concurrent test 2', async () => { /* ... */ })

.('sequential test 1', async () => { /* ... */ })
.('sequential test 2', async () => { /* ... */ })

// within concurrent suite
.('suite', () => {
  ('concurrent test 1', async () => { /* ... */ })
  ('concurrent test 2', async () => { /* ... */ })

  .('sequential test 1', async () => { /* ... */ })
  .('sequential test 2', async () => { /* ... */ })
})

test.todo

  • エイリアス: it.todo

後で実装するテストのスタブには、test.todoを使用します。レポートにはテストのエントリが表示されるため、実装する必要があるテストの数がわかります。

ts
// An entry will be shown in the report for this test
test.todo('unimplemented test')

test.fails

  • エイリアス: it.fails

アサーションが明示的に失敗することを示すには、test.failsを使用します。

ts
import { ,  } from 'vitest'

function () {
  return new ( => (1))
}
.('fail test', async () => {
  await (())..(1)
})

警告

Vitestを型チェッカーとして使用している場合は、この構文を使用できません。

test.each

  • エイリアス: it.each

異なる変数で同じテストを実行する必要がある場合は、test.eachを使用します。テスト関数のパラメーターの順に、テスト名でprintf書式設定を使用してパラメーターを挿入できます。

  • %s: 文字列
  • %d: 数値
  • %i: 整数
  • %f: 浮動小数点値
  • %j: json
  • %o: オブジェクト
  • %#: テストケースのインデックス
  • %%: 単一のパーセント記号 ('%')
ts
.([
  [1, 1, 2],
  [1, 2, 3],
  [2, 1, 3],
])('add(%i, %i) -> %i', (, , ) => {
  ( + ).()
})

// this will return
// ✓ add(1, 1) -> 2
// ✓ add(1, 2) -> 3
// ✓ add(2, 1) -> 3

引数としてオブジェクトを使用している場合は、$プレフィックスを使用してオブジェクトプロパティにアクセスすることもできます。

ts
test.each([
  { a: 1, b: 1, expected: 2 },
  { a: 1, b: 2, expected: 3 },
  { a: 2, b: 1, expected: 3 },
])('add($a, $b) -> $expected', ({ a, b, expected }) => {
  expect(a + b).toBe(expected)
})

// this will return
// ✓ add(1, 1) -> 2
// ✓ add(1, 2) -> 3
// ✓ add(2, 1) -> 3

引数としてオブジェクトを使用している場合は、.を使用してオブジェクト属性にアクセスすることもできます。

ts
test.each`
a               | b      | expected
${{ val: 1 }}   | ${'b'} | ${'1b'}
${{ val: 2 }}   | ${'b'} | ${'2b'}
${{ val: 3 }}   | ${'b'} | ${'3b'}
`('add($a.val, $b) -> $expected', ({ a, b, expected }) => {
  expect(a.val + b).toBe(expected)
})

// this will return
// ✓ add(1, b) -> 1b
// ✓ add(2, b) -> 2b
// ✓ add(3, b) -> 3b

Vitest 0.25.3以降では、テンプレート文字列テーブルも使用できます。

  • 最初の行は、|で区切られた列名である必要があります。
  • ${value}構文を使用してテンプレートリテラル式として提供される1つ以上の後続のデータ行。
ts
.`
  a               | b      | expected
  ${1}            | ${1}   | ${2}
  ${'a'}          | ${'b'} | ${'ab'}
  ${[]}           | ${'b'} | ${'b'}
  ${{}}           | ${'b'} | ${'[object Object]b'}
  ${{ : 1 }}   | ${'b'} | ${'[object Object]b'}
`('returns $expected when $a is added $b', ({ , ,  }) => {
  ( + ).()
})

TestContextにアクセスしたい場合は、単一のテストでdescribe.eachを使用します。

ヒント

Vitestは、Chaiのformatメソッドで$valuesを処理します。値が切り詰められすぎている場合は、設定ファイルでchaiConfig.truncateThresholdを増やすことができます。

警告

Vitestを型チェッカーとして使用している場合は、この構文を使用できません。

bench

  • 型: (name: string | Function, fn: BenchFunction, options?: BenchOptions) => void

benchはベンチマークを定義します。Vitestの用語では、ベンチマークは一連の操作を定義する関数です。Vitestはこの関数を複数回実行して、さまざまなパフォーマンス結果を表示します。

Vitestは、内部的にtinybenchライブラリを使用しており、3番目の引数として使用できるすべてのオプションを継承しています。

ts
import {  } from 'vitest'

('normal sorting', () => {
  const  = [1, 5, 4, 2, 3]
  .((, ) => {
    return  - 
  })
}, { : 1000 })
ts
export interface Options {
  /**
   * time needed for running a benchmark task (milliseconds)
   * @default 500
   */
  time?: number

  /**
   * number of times that a task should run if even the time option is finished
   * @default 10
   */
  iterations?: number

  /**
   * function to get the current timestamp in milliseconds
   */
  now?: () => number

  /**
   * An AbortSignal for aborting the benchmark
   */
  signal?: AbortSignal

  /**
   * warmup time (milliseconds)
   * @default 100ms
   */
  warmupTime?: number

  /**
   * warmup iterations
   * @default 5
   */
  warmupIterations?: number

  /**
   * setup function to run before each benchmark task (cycle)
   */
  setup?: Hook

  /**
   * teardown function to run after each benchmark task (cycle)
   */
  teardown?: Hook
}

bench.skip

  • 型: (name: string | Function, fn: BenchFunction, options?: BenchOptions) => void

bench.skip構文を使用して、特定のベンチマークの実行をスキップできます。

ts
import {  } from 'vitest'

.('normal sorting', () => {
  const  = [1, 5, 4, 2, 3]
  .((, ) => {
    return  - 
  })
})

bench.only

  • 型: (name: string | Function, fn: BenchFunction, options?: BenchOptions) => void

特定のスイートで特定のベンチマークのみを実行するには、bench.onlyを使用します。これはデバッグ時に役立ちます。

ts
import {  } from 'vitest'

.('normal sorting', () => {
  const  = [1, 5, 4, 2, 3]
  .((, ) => {
    return  - 
  })
})

bench.todo

  • 型: (name: string | Function) => void

後で実装するベンチマークのスタブには、bench.todoを使用します。

ts
import {  } from 'vitest'

.('unimplemented test')

describe

ファイルのトップレベルでtestまたはbenchを使用すると、それらは暗黙的なスイートの一部として収集されます。describeを使用すると、現在のコンテキストで、関連するテストまたはベンチマーク、およびその他のネストされたスイートのセットとして、新しいスイートを定義できます。スイートを使用すると、テストとベンチマークを整理して、レポートをより明確にすることができます。

ts
// basic.spec.ts
// organizing tests

import { , ,  } from 'vitest'

const  = {
  : true,
  : 32,
}

('person', () => {
  ('person is defined', () => {
    ().()
  })

  ('is active', () => {
    (.).()
  })

  ('age limit', () => {
    (.).(32)
  })
})
ts
// basic.bench.ts
// organizing benchmarks

import { ,  } from 'vitest'

('sort', () => {
  ('normal', () => {
    const  = [1, 5, 4, 2, 3]
    .((, ) => {
      return  - 
    })
  })

  ('reverse', () => {
    const  = [1, 5, 4, 2, 3]
    .().((, ) => {
      return  - 
    })
  })
})

テストまたはベンチマークの階層がある場合は、describeブロックをネストすることもできます。

ts
import { , ,  } from 'vitest'

function (: number | string) {
  if (typeof  !== 'number')
    throw new ('Value must be a number')

  return .(2).().(/\B(?=(\d{3})+(?!\d))/g, ',')
}

('numberToCurrency', () => {
  ('given an invalid number', () => {
    ('composed of non-numbers to throw error', () => {
      (() => ('abc')).()
    })
  })

  ('given a valid number', () => {
    ('returns the correct currency format', () => {
      ((10000)).('10,000.00')
    })
  })
})

describe.skip

  • エイリアス: suite.skip

特定のdescribeブロックの実行を回避するには、スイートでdescribe.skipを使用します。

ts
import { , ,  } from 'vitest'

.('skipped suite', () => {
  ('sqrt', () => {
    // Suite skipped, no error
    .(.(4), 3)
  })
})

describe.skipIf

  • エイリアス: suite.skipIf

場合によっては、環境が異なる状態でスイートを複数回実行することがあり、一部のスイートは環境固有の場合があります。スイートをifでラップする代わりに、条件がtrueの場合はいつでもdescribe.skipIfを使用してスイートをスキップできます。

ts
import { ,  } from 'vitest'

const  = .. === 'development'

.()('prod only test suite', () => {
  // this test suite only runs in production
})

警告

Vitestを型チェッカーとして使用している場合は、この構文を使用できません。

describe.runIf

  • エイリアス: suite.runIf

describe.skipIfの反対。

ts
import { , ,  } from 'vitest'

const  = .. === 'development'

.()('dev only test suite', () => {
  // this test suite only runs in development
})

警告

Vitestを型チェッカーとして使用している場合は、この構文を使用できません。

describe.only

  • 型: (name: string | Function, fn: TestFunction, options?: number | TestOptions) => void

特定のスイートのみを実行するには、describe.onlyを使用します。

ts
// Only this suite (and others marked with only) are run
.('suite', () => {
  ('sqrt', () => {
    .(.(4), 3)
  })
})

('other suite', () => {
  // ... will be skipped
})

出力が乱雑になるため、テストスイート全体から他のすべてのテストを無視して、特定のファイルでonlyテストを実行することが非常に便利な場合があります。

そのためには、対象のテストを含む特定のファイルでvitestを実行します。

# vitest interesting.test.ts

describe.concurrent

  • エイリアス: suite.concurrent

スイート内のdescribe.concurrentは、すべてのテストを同時実行としてマークします。

ts
// All tests within this suite will be run in parallel
.('suite', () => {
  ('concurrent test 1', async () => { /* ... */ })
  ('concurrent test 2', async () => { /* ... */ })
  .('concurrent test 3', async () => { /* ... */ })
})

.skip.only、および.todoは、同時スイートで機能します。次のすべての組み合わせは有効です。

ts
describe.concurrent(/* ... */)
describe.skip.concurrent(/* ... */) // or describe.concurrent.skip(/* ... */)
describe.only.concurrent(/* ... */) // or describe.concurrent.only(/* ... */)
describe.todo.concurrent(/* ... */) // or describe.concurrent.todo(/* ... */)

並行テストを実行する場合、スナップショットとアサーションは、正しいテストが検出されるように、ローカルのテストコンテキストからexpectを使用する必要があります。

ts
describe.concurrent('suite', () => {
  test('concurrent test 1', async ({ expect }) => {
    expect(foo).toMatchSnapshot()
  })
  test('concurrent test 2', async ({ expect }) => {
    expect(foo).toMatchSnapshot()
  })
})

警告

Vitestを型チェッカーとして使用している場合は、この構文を使用できません。

describe.sequential

  • エイリアス: suite.sequential

スイート内のdescribe.sequentialは、すべてのテストをシーケンシャルとしてマークします。これは、describe.concurrent内または--sequence.concurrentコマンドオプションでテストを順番に実行したい場合に役立ちます。

ts
.('suite', () => {
  ('concurrent test 1', async () => { /* ... */ })
  ('concurrent test 2', async () => { /* ... */ })

  .('', () => {
    ('sequential test 1', async () => { /* ... */ })
    ('sequential test 2', async () => { /* ... */ })
  })
})

describe.shuffle

  • エイリアス: suite.shuffle

Vitestは、CLIフラグ--sequence.shuffleまたは設定オプションsequence.shuffleを使用して、すべてのテストをランダムな順序で実行する方法を提供しますが、テストスイートの一部のみをランダムな順序で実行したい場合は、このフラグでマークできます。

ts
.('suite', () => {
  ('random test 1', async () => { /* ... */ })
  ('random test 2', async () => { /* ... */ })
  ('random test 3', async () => { /* ... */ })
})
// order depends on sequence.seed option in config (Date.now() by default)

.skip.only、および.todoは、ランダムスイートで機能します。

警告

Vitestを型チェッカーとして使用している場合は、この構文を使用できません。

describe.todo

  • エイリアス: suite.todo

describe.todo は、後で実装するスイートのスタブとして使用します。レポートにエントリが表示されるため、実装する必要のあるテストの数を把握できます。

ts
// An entry will be shown in the report for this suite
describe.todo('unimplemented suite')

describe.each

  • エイリアス: suite.each

同じデータに依存する複数のテストがある場合は、describe.each を使用します。

ts
.([
  { : 1, : 1, : 2 },
  { : 1, : 2, : 3 },
  { : 2, : 1, : 3 },
])('describe object add($a, $b)', ({ , ,  }) => {
  (`returns ${}`, () => {
    ( + ).()
  })

  (`returned value not be greater than ${}`, () => {
    ( + )..()
  })

  (`returned value not be less than ${}`, () => {
    ( + )..()
  })
})

Vitest 0.25.3以降では、テンプレート文字列テーブルも使用できます。

  • 最初の行は、|で区切られた列名である必要があります。
  • ${value}構文を使用してテンプレートリテラル式として提供される1つ以上の後続のデータ行。
ts
.`
  a               | b      | expected
  ${1}            | ${1}   | ${2}
  ${'a'}          | ${'b'} | ${'ab'}
  ${[]}           | ${'b'} | ${'b'}
  ${{}}           | ${'b'} | ${'[object Object]b'}
  ${{ : 1 }}   | ${'b'} | ${'[object Object]b'}
`('describe template string add($a, $b)', ({ , ,  }) => {
  (`returns ${}`, () => {
    ( + ).()
  })
})

警告

Vitestを型チェッカーとして使用している場合は、この構文を使用できません。

セットアップとティアダウン

これらの関数を使用すると、テストのライフサイクルにフックして、セットアップおよびティアダウンコードの繰り返しを回避できます。これらは現在のコンテキストに適用されます。最上位レベルで使用されている場合はファイル、describe ブロック内にある場合は現在のスイートです。これらのフックは、Vitestを型チェッカーとして実行している場合は呼び出されません。

beforeEach

  • 型: beforeEach(fn: () => Awaitable<void>, timeout?: number)

現在のコンテキストで実行される各テストの前に呼び出されるコールバックを登録します。関数がPromiseを返す場合、VitestはPromiseが解決されるまで待ってからテストを実行します。

オプションで、タイムアウト(ミリ秒単位)を渡して、終了するまで待機する時間を定義できます。デフォルトは5秒です。

ts
import { beforeEach } from 'vitest'

beforeEach(async () => {
  // Clear mocks and add some testing data after before each test run
  await stopMocking()
  await addUser({ name: 'John' })
})

ここでは、beforeEach は各テストでユーザーが追加されることを保証します。

Vitest v0.10.0 以降、beforeEach はオプションのクリーンアップ関数(afterEach と同等)も受け入れるようになりました。

ts
import { beforeEach } from 'vitest'

beforeEach(async () => {
  // called once before each test run
  await prepareSomething()

  // clean up function, called once after each test run
  return async () => {
    await resetSomething()
  }
})

afterEach

  • 型: afterEach(fn: () => Awaitable<void>, timeout?: number)

現在のコンテキストで各テストが完了した後、呼び出されるコールバックを登録します。関数がPromiseを返す場合、VitestはPromiseが解決されるまで待ってから続行します。

オプションで、終了するまで待機する時間を指定するためのタイムアウト(ミリ秒単位)を指定できます。デフォルトは5秒です。

ts
import { afterEach } from 'vitest'

afterEach(async () => {
  await clearTestingData() // clear testing data after each test run
})

ここでは、afterEach は各テストの実行後にテストデータがクリアされることを保証します。

ヒント

Vitest 1.3.0 で onTestFinished フックが追加されました。テスト実行中に呼び出して、テストの実行が完了した後の状態をクリーンアップできます。

beforeAll

  • 型: beforeAll(fn: () => Awaitable<void>, timeout?: number)

現在のコンテキストで、すべてのテストの実行を開始する前に一度だけ呼び出されるコールバックを登録します。関数がPromiseを返す場合、VitestはPromiseが解決されるまで待ってからテストを実行します。

オプションで、終了するまで待機する時間を指定するためのタイムアウト(ミリ秒単位)を指定できます。デフォルトは5秒です。

ts
import { beforeAll } from 'vitest'

beforeAll(async () => {
  await startMocking() // called once before all tests run
})

ここでは、beforeAll はテストの実行前にモックデータが設定されることを保証します。

Vitest v0.10.0 以降、beforeAll はオプションのクリーンアップ関数(afterAll と同等)も受け入れるようになりました。

ts
import { beforeAll } from 'vitest'

beforeAll(async () => {
  // called once before all tests run
  await startMocking()

  // clean up function, called once after all tests run
  return async () => {
    await stopMocking()
  }
})

afterAll

  • 型: afterAll(fn: () => Awaitable<void>, timeout?: number)

現在のコンテキストで、すべてのテストが実行された後に一度だけ呼び出されるコールバックを登録します。関数がPromiseを返す場合、VitestはPromiseが解決されるまで待ってから続行します。

オプションで、終了するまで待機する時間を指定するためのタイムアウト(ミリ秒単位)を指定できます。デフォルトは5秒です。

ts
import { afterAll } from 'vitest'

afterAll(async () => {
  await stopMocking() // this method is called after all tests run
})

ここでは、afterAll はすべてのテストの実行後に stopMocking メソッドが呼び出されることを保証します。

テストフック

Vitest は、テストの実行中に呼び出して、テストの実行が完了したときに状態をクリーンアップできるいくつかのフックを提供します。

警告

これらのフックは、テスト本体の外で呼び出された場合、エラーをスローします。

onTestFinished 1.3.0+

このフックは、テストの実行が完了した後に常に呼び出されます。テスト結果に影響を与える可能性があるため、afterEach フックの後に呼び出されます。現在のテスト結果を示す TaskResult オブジェクトを受け取ります。

ts
import { onTestFinished, test } from 'vitest'

test('performs a query', () => {
  const db = connectDb()
  onTestFinished(() => db.close())
  db.query('SELECT * FROM users')
})

警告

テストを同時実行している場合は、Vitest はグローバルフックで同時実行テストを追跡しないため、常にテストコンテキストから onTestFinished フックを使用する必要があります。

ts
import { test } from 'vitest'

test.concurrent('performs a query', ({ onTestFinished }) => {
  const db = connectDb()
  onTestFinished(() => db.close())
  db.query('SELECT * FROM users')
})

このフックは、再利用可能なロジックを作成するときに特に役立ちます

ts
// this can be in a separate file
function getTestDb() {
  const db = connectMockedDb()
  onTestFinished(() => db.close())
  return db
}

test('performs a user query', async () => {
  const db = getTestDb()
  expect(
    await db.query('SELECT * from users').perform()
  ).toEqual([])
})

test('performs an organization query', async () => {
  const db = getTestDb()
  expect(
    await db.query('SELECT * from organizations').perform()
  ).toEqual([])
})

ヒント

このフックは常に逆順で呼び出され、sequence.hooks オプションの影響を受けません。

onTestFailed

このフックは、テストが失敗した場合にのみ呼び出されます。テスト結果に影響を与える可能性があるため、afterEach フックの後に呼び出されます。現在のテスト結果を示す TaskResult オブジェクトを受け取ります。このフックはデバッグに役立ちます。

ts
import { onTestFailed, test } from 'vitest'

test('performs a query', () => {
  const db = connectDb()
  onTestFailed((e) => {
    console.log(e.result.errors)
  })
  db.query('SELECT * FROM users')
})

警告

テストを同時実行している場合は、Vitest はグローバルフックで同時実行テストを追跡しないため、常にテストコンテキストから onTestFailed フックを使用する必要があります。

ts
import { test } from 'vitest'

test.concurrent('performs a query', ({ onTestFailed }) => {
  const db = connectDb()
  onTestFailed((result) => {
    console.log(result.errors)
  })
  db.query('SELECT * FROM users')
})

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