メインコンテンツへスキップ
バージョン: 次へ

グローバル API

非公式ベータ版翻訳

このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →

テストファイル内では、Jest は以下の各メソッドとオブジェクトをグローバル環境に配置します。これらを使用するために require や import する必要はありません。ただし、明示的なインポートを希望する場合は、import {describe, expect, test} from '@jest/globals' のように記述できます。

非公式ベータ版翻訳

このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →

情報

このページのTypeScriptの例は、JestのAPIを明示的にインポートした場合にのみ、ドキュメント通りに動作します:

import {expect, jest, test} from '@jest/globals';

TypeScriptでJestを設定する方法の詳細については、はじめにガイドを参照してください。

メソッド


リファレンス

afterAll(fn, timeout)

このファイル内のすべてのテストが完了した後に関数を実行します。関数がプロミスを返す場合やジェネレータである場合、Jest は処理を続行する前にそのプロミスが解決されるまで待機します。

オプションとして、timeout(ミリ秒単位)を指定して、中止までの待機時間を設定できます。デフォルトのタイムアウトは5秒です。

複数のテスト間で共有されるグローバルな設定状態をクリーンアップする場合に特に有用です。

例:

const globalDatabase = makeGlobalDatabase();

function cleanUpDatabase(db) {
db.cleanUp();
}

afterAll(() => {
cleanUpDatabase(globalDatabase);
});

test('can find things', () => {
return globalDatabase.find('thing', {}, results => {
expect(results.length).toBeGreaterThan(0);
});
});

test('can insert a thing', () => {
return globalDatabase.insert('thing', makeThing(), response => {
expect(response.success).toBeTruthy();
});
});

ここでは afterAll によって、すべてのテスト実行後に cleanUpDatabase が呼び出されることが保証されます。

afterAlldescribe ブロック内にある場合、describe ブロックの終了時に実行されます。

すべてのテスト後ではなく各テストの後にクリーンアップを実行したい場合は、代わりに afterEach を使用してください。

afterEach(fn, timeout)

このファイル内の各テストが完了するたびに関数を実行します。関数がプロミスを返す場合やジェネレータである場合、Jest は処理を続行する前にそのプロミスが解決されるまで待機します。

オプションとして、timeout(ミリ秒単位)を指定して、中止までの待機時間を設定できます。デフォルトのタイムアウトは5秒です。

各テストで作成される一時的な状態をクリーンアップする場合に特に有用です。

例:

const globalDatabase = makeGlobalDatabase();

function cleanUpDatabase(db) {
db.cleanUp();
}

afterEach(() => {
cleanUpDatabase(globalDatabase);
});

test('can find things', () => {
return globalDatabase.find('thing', {}, results => {
expect(results.length).toBeGreaterThan(0);
});
});

test('can insert a thing', () => {
return globalDatabase.insert('thing', makeThing(), response => {
expect(response.success).toBeTruthy();
});
});

ここでは afterEach によって、各テスト実行後に cleanUpDatabase が呼び出されることが保証されます。

afterEachdescribe ブロック内にある場合、その describe ブロック内のテストの後にのみ実行されます。

すべてのテスト実行後に1回だけクリーンアップを実行したい場合は、代わりに afterAll を使用してください。

beforeAll(fn, timeout)

このファイル内のいずれのテストよりも前に関数を実行します。関数がプロミスを返す場合やジェネレータである場合、Jest はテストを実行する前にそのプロミスが解決されるまで待機します。

オプションとして、timeout(ミリ秒単位)を指定して、中止までの待機時間を設定できます。デフォルトのタイムアウトは5秒です。

複数のテストで使用されるグローバルな状態をセットアップする場合に特に有用です。

例:

const globalDatabase = makeGlobalDatabase();

beforeAll(() => {
// Clears the database and adds some testing data.
// Jest will wait for this promise to resolve before running tests.
return globalDatabase.clear().then(() => {
return globalDatabase.insert({testData: 'foo'});
});
});

// Since we only set up the database once in this example, it's important
// that our tests don't modify it.
test('can find things', () => {
return globalDatabase.find('thing', {}, results => {
expect(results.length).toBeGreaterThan(0);
});
});

ここでは beforeAll によって、テスト実行前にデータベースがセットアップされることが保証されます。セットアップが同期的な場合は beforeAll なしでも可能です。重要な点は、Jest がプロミスの解決を待つため、非同期セットアップも可能であることです。

beforeAlldescribe ブロック内にある場合、describe ブロックの開始時に実行されます。

すべてのテストの前ではなく各テストの前に実行したい場合は、代わりに beforeEach を使用してください。

beforeEach(fn, timeout)

このファイル内の各テストが実行される前に毎回関数を実行します。関数がプロミスを返す場合やジェネレータである場合、Jest はテストを実行する前にそのプロミスが解決されるまで待機します。

オプションとして、timeout(ミリ秒単位)を指定して、中止までの待機時間を設定できます。デフォルトのタイムアウトは5秒です。

複数のテストで使用されるグローバルな状態をリセットする場合に特に有用です。

例:

const globalDatabase = makeGlobalDatabase();

beforeEach(() => {
// Clears the database and adds some testing data.
// Jest will wait for this promise to resolve before running tests.
return globalDatabase.clear().then(() => {
return globalDatabase.insert({testData: 'foo'});
});
});

test('can find things', () => {
return globalDatabase.find('thing', {}, results => {
expect(results.length).toBeGreaterThan(0);
});
});

test('can insert a thing', () => {
return globalDatabase.insert('thing', makeThing(), response => {
expect(response.success).toBeTruthy();
});
});

ここでは beforeEach によって、各テストごとにデータベースがリセットされることが保証されます。

beforeEachdescribeブロック内にある場合、そのブロック内の各テストの前に実行されます。

もしセットアップコードを一度だけ(すべてのテストの前で)実行したい場合は、代わりにbeforeAllを使用してください。

describe(name, fn)

describe(name, fn)は、関連する複数のテストをグループ化するブロックを作成します。例えば、myBeverageオブジェクトが美味しくて酸っぱくないことをテストする場合:

const myBeverage = {
delicious: true,
sour: false,
};

describe('my beverage', () => {
test('is delicious', () => {
expect(myBeverage.delicious).toBeTruthy();
});

test('is not sour', () => {
expect(myBeverage.sour).toBeFalsy();
});
});

これは必須ではありません──トップレベルに直接testブロックを記述することも可能です。ただし、テストをグループ化して整理したい場合に便利です。

テスト階層がある場合、describeブロックをネストさせることもできます:

const binaryStringToNumber = binString => {
if (!/^[01]+$/.test(binString)) {
throw new CustomError('Not a binary number.');
}

return parseInt(binString, 2);
};

describe('binaryStringToNumber', () => {
describe('given an invalid binary string', () => {
test('composed of non-numbers throws CustomError', () => {
expect(() => binaryStringToNumber('abc')).toThrow(CustomError);
});

test('with extra whitespace throws CustomError', () => {
expect(() => binaryStringToNumber(' 100')).toThrow(CustomError);
});
});

describe('given a valid binary string', () => {
test('returns the correct number', () => {
expect(binaryStringToNumber('100')).toBe(4);
});
});
});

describe.each(table)(name, fn, timeout)

異なるデータで同じテストスイートを重複して書く場合、describe.eachを使用してください。describe.eachを使えばテストスイートを一度記述するだけで、データを渡せます。

describe.eachには2つのAPI形式があります:

1. describe.each(table)(name, fn, timeout)

  • table: Array の配列。各行の引数としてfnに渡されます。プリミティブ型の1次元配列を渡すと、内部的にテーブルにマッピングされます(例:[1, 2, 3] -> [[1], [2], [3]])。

  • name: String テストスイートのタイトル。

    • printf書式でパラメータを位置指定挿入して一意なテストタイトルを生成:
      • %p - pretty-format
      • %s - 文字列
      • %d - 数値
      • %i - 整数
      • %f - 浮動小数点数
      • %j - JSON
      • %o - オブジェクト
      • %# - テストケースのインデックス
      • %$ - テストケース番号
      • %% - パーセント記号自体(引数を消費しません)
    • または$variableでテストケースオブジェクトのプロパティを挿入:
      • ネストされたオブジェクトはキーパスで指定可能(例:$variable.path.to.value)。ただし独自プロパティのみ有効(例:$variable.constructor.nameは不可)
      • $#でテストケースのインデックスを挿入可能
      • printf書式と$variableは併用不可(%%を除く)
  • fn: 実行するテストスイート(Function)。各行のパラメータが引数として渡されます。

  • オプションとして、timeout(ミリ秒単位)を指定して、各テストケースが中止されるまで待機する時間を設定できます。デフォルトのタイムアウトは5秒です。

例:

describe.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected);
});

test(`returned value not be greater than ${expected}`, () => {
expect(a + b).not.toBeGreaterThan(expected);
});

test(`returned value not be less than ${expected}`, () => {
expect(a + b).not.toBeLessThan(expected);
});
});
describe.each([
{a: 1, b: 1, expected: 2},
{a: 1, b: 2, expected: 3},
{a: 2, b: 1, expected: 3},
])('.add($a, $b)', ({a, b, expected}) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected);
});

test(`returned value not be greater than ${expected}`, () => {
expect(a + b).not.toBeGreaterThan(expected);
});

test(`returned value not be less than ${expected}`, () => {
expect(a + b).not.toBeLessThan(expected);
});
});

2. describe.each`table`(name, fn, timeout)

  • table: Tagged Template Literal

    • 1行目:|で区切った変数名の列見出し
    • 2行目以降:${value}構文でデータを提供
  • name: テストスイートのタイトル(String)。$variableでテンプレート式のデータを挿入、$#で行インデックスを挿入

    • ネストされたオブジェクトはキーパスで指定可能(例:$variable.path.to.value)。ただし独自プロパティのみ有効(例: $variable.constructor.name は動作しません)
  • fn: Function 実行するテストスイート。この関数はテストデータオブジェクトを引数として受け取ります。

  • オプションとして、timeout(ミリ秒単位)を指定して、各テストケースが中止されるまで待機する時間を設定できます。デフォルトのタイムアウトは5秒です。

例:

describe.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('$a + $b', ({a, b, expected}) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected);
});

test(`returned value not be greater than ${expected}`, () => {
expect(a + b).not.toBeGreaterThan(expected);
});

test(`returned value not be less than ${expected}`, () => {
expect(a + b).not.toBeLessThan(expected);
});
});

describe.only(name, fn)

別名: fdescribe(name, fn)

特定のdescribeブロックのみを実行したい場合、describe.onlyを使用できます:

describe.only('my beverage', () => {
test('is delicious', () => {
expect(myBeverage.delicious).toBeTruthy();
});

test('is not sour', () => {
expect(myBeverage.sour).toBeFalsy();
});
});

describe('my other beverage', () => {
// ... will be skipped
});

describe.only.each(table)(name, fn)

別名: fdescribe.each(table)(name, fn) および fdescribe.each`table`(name, fn)

データ駆動テストの特定のテストスイートのみを実行したい場合、describe.only.eachを使用します。

describe.only.eachは2つのAPI形式で利用できます:

describe.only.each(table)(name, fn)

describe.only.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected);
});
});

test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});

describe.only.each`table`(name, fn)

describe.only.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
test('passes', () => {
expect(a + b).toBe(expected);
});
});

test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});

describe.skip(name, fn)

別名: xdescribe(name, fn)

特定のdescribeブロックのテストを実行したくない場合、describe.skipを使用できます:

describe('my beverage', () => {
test('is delicious', () => {
expect(myBeverage.delicious).toBeTruthy();
});

test('is not sour', () => {
expect(myBeverage.sour).toBeFalsy();
});
});

describe.skip('my other beverage', () => {
// ... will be skipped
});

describe.skipは、テストの塊を一時的にコメントアウトするよりクリーンな代替手段です。ただしdescribeブロック自体は実行される点に注意してください。スキップしたいセットアップがある場合は、beforeAllbeforeEachブロック内で行ってください。

describe.skip.each(table)(name, fn)

別名: xdescribe.each(table)(name, fn) および xdescribe.each`table`(name, fn)

データ駆動テストのスイート実行を停止したい場合、describe.skip.eachを使用します。

describe.skip.eachは2つのAPI形式で利用できます:

describe.skip.each(table)(name, fn)

describe.skip.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected); // will not be run
});
});

test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});

describe.skip.each`table`(name, fn)

describe.skip.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
test('will not be run', () => {
expect(a + b).toBe(expected); // will not be run
});
});

test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});

test(name, fn, timeout)

別名: it(name, fn, timeout)

テストファイルでは、テストを実行するtestメソッドがあれば十分です。例えばinchesOfRain()関数がゼロを返すべき場合、テスト全体は次のようになります:

test('did not rain', () => {
expect(inchesOfRain()).toBe(0);
});

第1引数はテスト名、第2引数はテストする期待値を含む関数です。第3引数(オプション)はtimeout(ミリ秒単位)で、中断までの待機時間を指定します。デフォルトのタイムアウトは5秒です。

testからPromiseが返される場合、Jestはテスト完了前にそのPromiseが解決されるまで待機します。例えばfetchBeverageList()lemonを含むリストで解決されるPromiseを返す場合:

test('has lemon in it', () => {
return fetchBeverageList().then(list => {
expect(list).toContain('lemon');
});
});

test呼び出しは即時返りますが、テストはPromiseが解決されるまで完了しません。詳細は非同期コードのテストページを参照してください。

ヒント

テスト関数に引数を渡す場合(通常doneと呼ばれます)、Jestはその引数が呼び出されるまで待機します。これはコールバックをテストする際に便利です。

test.concurrent(name, fn, timeout)

別名: it.concurrent(name, fn, timeout)

注意

test.concurrentは実験的な機能です。不足機能や課題の詳細はこちらをご覧ください。

テストを並行実行したい場合、test.concurrentを使用します。

最初の引数はテスト名、2番目の引数はテスト対象のアサーションを含む非同期関数です。3番目の引数(オプション)は中断までの待機時間をミリ秒で指定するtimeoutで、デフォルトは5秒です。

test.concurrent('addition of 2 numbers', async () => {
expect(5 + 3).toBe(8);
});

test.concurrent('subtraction 2 numbers', async () => {
expect(5 - 3).toBe(2);
});
ヒント

同時に実行するテスト数を制限するには、maxConcurrency設定オプションを使用してください。

test.concurrent.each(table)(name, fn, timeout)

エイリアス: it.concurrent.each(table)(name, fn, timeout)

同じテストを異なるデータで重複して書く場合、test.concurrent.eachを使用します。test.eachを使うと、テストを一度書くだけでデータを渡せ、すべてのテストが非同期で実行されます。

test.concurrent.eachには2つのAPI形式があります:

1. test.concurrent.each(table)(name, fn, timeout)

  • table: テスト関数fnに各行の引数として渡される配列のArray

    • プリミティブ値の1次元配列を渡す場合、内部的にテーブル形式に変換されます(例: [1, 2, 3] -> [[1], [2], [3]]
  • name: String テストブロックのタイトル

    • printf書式でパラメータを位置指定挿入して一意なテスト名を生成:
      • %p - pretty-format
      • %s - 文字列
      • %d - 数値
      • %i - 整数
      • %f - 浮動小数点数
      • %j - JSON
      • %o - オブジェクト
      • %# - テストケースのインデックス
      • %$ - テストケース番号
      • %% - パーセント記号('%')。引数を消費しません
  • fn: Function 実行するテスト関数。この関数は各行のパラメータを引数として受け取ります。非同期関数である必要があります

  • オプションとして、timeout(ミリ秒単位)を指定して、各テストケースが中止されるまで待機する時間を設定できます。デフォルトのタイムアウトは5秒です。

例:

test.concurrent.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', async (a, b, expected) => {
expect(a + b).toBe(expected);
});

2. test.concurrent.each`table`(name, fn, timeout)

  • table: Tagged Template Literal

    • 1行目:|で区切った変数名の列見出し
    • 2行目以降:${value}構文でデータを提供
  • name: String テストのタイトル。タグ付きテンプレート式から$variableでテストデータを挿入可能

    • オブジェクトのネストした値はキーパスで指定(例: $variable.path.to.value)。ただし独自プロパティのみ有効(例: $variable.constructor.nameは非対応)
  • fn: Function 実行するテスト関数。この関数はテストデータオブジェクトを受け取ります。非同期関数である必要があります

  • オプションとして、timeout(ミリ秒単位)を指定して、各テストケースが中止されるまで待機する時間を設定できます。デフォルトのタイムアウトは5秒です。

例:

test.concurrent.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', async ({a, b, expected}) => {
expect(a + b).toBe(expected);
});

test.concurrent.only.each(table)(name, fn)

エイリアス: it.concurrent.only.each(table)(name, fn)

特定のテストデータパターンのみを並列実行したい場合、test.concurrent.only.eachを使用します。

test.concurrent.only.eachには2つのAPI形式があります:

test.concurrent.only.each(table)(name, fn)

test.concurrent.only.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', async (a, b, expected) => {
expect(a + b).toBe(expected);
});

test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.only.each`table`(name, fn)

test.concurrent.only.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', async ({a, b, expected}) => {
expect(a + b).toBe(expected);
});

test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.concurrent.skip.each(table)(name, fn)

別名として: it.concurrent.skip.each(table)(name, fn)

非同期のデータ駆動テストのセットを実行停止したい場合、test.concurrent.skip.eachを使用します。

test.concurrent.skip.eachは2つのAPI形式で利用可能です:

test.concurrent.skip.each(table)(name, fn)

test.concurrent.skip.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', async (a, b, expected) => {
expect(a + b).toBe(expected); // will not be run
});

test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.concurrent.skip.each`table`(name, fn)

test.concurrent.skip.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', async ({a, b, expected}) => {
expect(a + b).toBe(expected); // will not be run
});

test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.each(table)(name, fn, timeout)

別名として: it.each(table)(name, fn) および it.each`table`(name, fn)

同じテストを異なるデータで重複して記述している場合、test.eachを使用します。test.eachはテストを一度記述し、データを渡すことを可能にします。

test.eachは2つのAPI形式で利用可能です:

1. test.each(table)(name, fn, timeout)

  • table: テスト関数fnに各行の引数として渡される配列のArray

    • プリミティブ値の1次元配列を渡す場合、内部的にテーブル形式に変換されます(例: [1, 2, 3] -> [[1], [2], [3]]
  • name: テストブロックのタイトル(String

    • printf 書式設定でパラメータを位置指定挿入して一意なテストタイトルを生成:
      • %p - pretty-format
      • %s - 文字列
      • %d - 数値
      • %i - 整数
      • %f - 浮動小数点数
      • %j - JSON
      • %o - オブジェクト
      • %# - テストケースのインデックス
      • %$ - テストケースの番号
      • %% - パーセント記号(引数を消費しません)
    • またはテストケースオブジェクトのプロパティを$variableで挿入して一意なテストタイトルを生成:
      • ネストされたオブジェクト値を挿入するにはキーパスを指定(例: $variable.path.to.value独自プロパティのみ有効。$variable.constructor.nameは非対応)
      • $#でテストケースのインデックスを挿入可能
    • $variable%%を除きprintf書式設定と併用不可
  • fn: 実行するテスト関数(Function)。各行のパラメータを引数として受け取ります。

  • オプションとして、timeout(ミリ秒単位)を指定して、各テストケースが中止されるまで待機する時間を設定できます。デフォルトのタイムアウトは5秒です。

例:

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

2. test.each`table`(name, fn, timeout)

  • table: Tagged Template Literal

    • 1行目:|で区切った変数名の列見出し
    • 2行目以降:${value}構文でデータを提供
  • name: String テストのタイトル。タグ付きテンプレート式から$variableでテストデータを挿入可能

    • オブジェクトのネストした値はキーパスで指定(例: $variable.path.to.value)。ただし独自プロパティのみ有効(例: $variable.constructor.nameは非対応)
  • fn: 実行するテスト関数(Function)。テストデータオブジェクトを受け取ります。

  • オプションとして、timeout(ミリ秒単位)を指定して、各テストケースが中止されるまで待機する時間を設定できます。デフォルトのタイムアウトは5秒です。

例:

test.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
expect(a + b).toBe(expected);
});

test.failing(name, fn, timeout)

別名: it.failing(name, fn, timeout)

メモ

この機能はデフォルトのjest-circusランナーでのみ利用可能です。

test.failingは、失敗することを期待してテストを書く場合に使用します。これらのテストは通常のテストとは逆の動作をします。failingテストがエラーをスローするとテストは成功し、エラーをスローしない場合は失敗とみなされます。

ヒント

BDDスタイルでコードを書いている場合などにこのテスト形式を活用できます。テストが成功するまでは失敗として表示されないため、テストがパスする準備ができたらfailing修飾子を削除すればよいでしょう。

バグ修正方法が分からなくても、プロジェクトに失敗するテストケースを提供する方法としても有用です。

例:

test.failing('it is not equal', () => {
expect(5).toBe(6); // this test will pass
});

test.failing('it is equal', () => {
expect(10).toBe(10); // this test will fail
});

test.failing.each(name, fn, timeout)

別名: it.failing.each(table)(name, fn) および it.failing.each`table`(name, fn)

メモ

この機能はデフォルトのjest-circusランナーでのみ利用可能です。

failingeachを追加することで、複数の失敗予想テストをまとめて実行できます。

例:

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

test.only.failing(name, fn, timeout)

別名: it.only.failing(name, fn, timeout), fit.failing(name, fn, timeout)

メモ

この機能はデフォルトのjest-circusランナーでのみ利用可能です。

特定の失敗予想テストのみを実行したい場合にtest.only.failingを使用します。

test.skip.failing(name, fn, timeout)

別名: it.skip.failing(name, fn, timeout), xit.failing(name, fn, timeout), xtest.failing(name, fn, timeout)

メモ

この機能はデフォルトのjest-circusランナーでのみ利用可能です。

特定の失敗予想テストをスキップしたい場合にtest.skip.failingを使用します。

test.only(name, fn, timeout)

別名: it.only(name, fn, timeout), fit(name, fn, timeout)

大規模なテストファイルをデバッグする際、特定のテストのみを実行したい場合があります。.onlyを使用すると、そのテストファイルで実行するテストを限定できます。

オプションとして、timeout(ミリ秒単位)を指定して、中止までの待機時間を設定できます。デフォルトのタイムアウトは5秒です。

例として、以下のテストがあるとします:

test.only('it is raining', () => {
expect(inchesOfRain()).toBeGreaterThan(0);
});

test('it is not snowing', () => {
expect(inchesOfSnow()).toBe(0);
});

test.onlyで実行されているため、このテストファイルでは「雨が降っている」テストのみが実行されます。

通常、test.onlyを使用したコードをソース管理にコミットすることはありません。デバッグ目的で使用し、問題が修正されたら削除します。

test.only.each(table)(name, fn)

エイリアスとして it.only.each(table)(name, fn), fit.each(table)(name, fn), it.only.each`table`(name, fn), fit.each`table`(name, fn) も利用可能です。

異なるテストデータで特定のテストのみを実行したい場合、test.only.each を使用します。

test.only.each は2種類のAPI形式で利用可能です:

test.only.each(table)(name, fn)

test.only.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
expect(a + b).toBe(expected);
});

test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.only.each`table`(name, fn)

test.only.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
expect(a + b).toBe(expected);
});

test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.skip(name, fn)

エイリアスとして it.skip(name, fn), xit(name, fn), xtest(name, fn) も利用可能です。

大規模なコードベースを保守している場合、一時的にテストが失敗する状態になることがあります。コードを削除せずにテスト実行をスキップしたい場合、test.skip を使用して特定のテストをスキップできます。

例として、以下のテストがあるとします:

test('it is raining', () => {
expect(inchesOfRain()).toBeGreaterThan(0);
});

test.skip('it is not snowing', () => {
expect(inchesOfSnow()).toBe(0);
});

test.skip で実行されたテストを除くため、「雨が降っている」テストのみが実行されます。

テストをコメントアウトすることも可能ですが、test.skip を使用するとインデントやシンタックスハイライトが維持されるため便利です。

test.skip.each(table)(name, fn)

エイリアスとして it.skip.each(table)(name, fn), xit.each(table)(name, fn), xtest.each(table)(name, fn), it.skip.each`table`(name, fn), xit.each`table`(name, fn), xtest.each`table`(name, fn) も利用可能です。

データ駆動テストの特定セットをスキップしたい場合、test.skip.each を使用します。

test.skip.each は2種類のAPI形式で利用可能です:

test.skip.each(table)(name, fn)

test.skip.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
expect(a + b).toBe(expected); // will not be run
});

test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.skip.each`table`(name, fn)

test.skip.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
expect(a + b).toBe(expected); // will not be run
});

test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.todo(name)

エイリアスとして it.todo(name) も利用可能です。

テストを今後作成予定の場合に test.todo を使用します。これらのテストは要約出力でハイライト表示されるため、残りのテスト数が把握できます。

const add = (a, b) => a + b;

test.todo('add should be associative');
ヒント

test.todo はテストコールバック関数を渡すとエラーをスローします。実装済みのテストを実行したくない場合は、代わりに test.skip を使用してください。

TypeScript 使用方法

非公式ベータ版翻訳

このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →

情報

このページのTypeScriptの例は、JestのAPIを明示的にインポートした場合にのみ、ドキュメント通りに動作します:

import {expect, jest, test} from '@jest/globals';

TypeScriptでJestを設定する方法の詳細については、はじめにガイドを参照してください。

.each

.each 修飾子はテストケースのテーブルを定義する複数の方法を提供します。一部のAPIには、describetest コールバック関数に渡される引数の型推論に関連する注意点があります。各形式を見ていきましょう。

メモ

例では簡略化のため test.each を使用していますが、型推論は .each 修飾子が利用可能な全てのケース(describe.each, test.concurrent.only.each, test.skip.each など)で同様です。

オブジェクトの配列

オブジェクトの配列APIは最も詳細ですが、型推論が容易です。tableはインラインで記述できます:

import {test} from '@jest/globals';

test.each([
{name: 'a', path: 'path/to/a', count: 1, write: true},
{name: 'b', path: 'path/to/b', count: 3},
])('inline table', ({name, path, count, write}) => {
// arguments are typed as expected, e.g. `write: boolean | undefined`
});

または変数として個別に宣言可能です:

import {test} from '@jest/globals';

const table = [
{a: 1, b: 2, expected: 'three', extra: true},
{a: 3, b: 4, expected: 'seven', extra: false},
{a: 5, b: 6, expected: 'eleven'},
];

test.each(table)('table as a variable', ({a, b, expected, extra}) => {
// again everything is typed as expected, e.g. `extra: boolean | undefined`
});

配列の配列

配列の配列形式はインラインテーブルで問題なく動作します:

import {test} from '@jest/globals';

test.each([
[1, 2, 'three', true],
[3, 4, 'seven', false],
[5, 6, 'eleven'],
])('inline table example', (a, b, expected, extra) => {
// arguments are typed as expected, e.g. `extra: boolean | undefined`
});

ただし、テーブルを個別変数として宣言する場合、正しい型推論のためタプルの配列として型指定が必要です(行の全要素が同じ型の場合は不要):

import {test} from '@jest/globals';

const table: Array<[number, number, string, boolean?]> = [
[1, 2, 'three', true],
[3, 4, 'seven', false],
[5, 6, 'eleven'],
];

test.each(table)('table as a variable example', (a, b, expected, extra) => {
// without the annotation types are incorrect, e.g. `a: number | string | boolean`
});

テンプレートリテラル

すべての入力値が同じ型の場合、テンプレートリテラルAPIは引数を正しく型付けします:

import {test} from '@jest/globals';

test.each`
a | b | expected
${1} | ${2} | ${3}
${3} | ${4} | ${7}
${5} | ${6} | ${11}
`('template literal example same type', ({a, b, expected}) => {
// all arguments are of type `number` because all inputs (a, b, expected) are of type `number`
});

入力値が異なる型を持つ場合、引数はすべての入力型のユニオン型として型付けされます(つまりテンプレートリテラル内の変数の型):

import {test} from '@jest/globals';

test.each`
a | b | expected
${1} | ${2} | ${'three'}
${3} | ${4} | ${'seven'}
${5} | ${6} | ${'eleven'}
`('template literal example different types', ({a, b, expected}) => {
// all arguments are of type `number | string` because some inputs (a, b) are of type `number` and some others (expected) are of type `string`
});

それ以外の場合、各引数に正しい型を持たせたい場合は、ジェネリック型引数を明示的に指定する必要があります:

import {test} from '@jest/globals';

test.each<{a: number; b: number; expected: string; extra?: boolean}>`
a | b | expected | extra
${1} | ${2} | ${'three'} | ${true}
${3} | ${4} | ${'seven'} | ${false}
${5} | ${6} | ${'eleven'}
`('template literal example', ({a, b, expected, extra}) => {
// all arguments are typed as expected, e.g. `a: number`, `expected: string`, `extra: boolean | undefined`
});
注意

テンプレートリテラル内の変数は型チェックされない点に注意してください。そのため、型が正しいことを自分で確認する必要があります。

import {test} from '@jest/globals';

test.each<{a: number; expected: string}>`
a | expected
${1} | ${'one'}
${'will not raise TS error'} | ${'two'}
${3} | ${'three'}
`('template literal with wrongly typed input', ({a, expected}) => {
// all arguments are typed as stated in the generic: `a: number`, `expected: string`
// WARNING: `a` is of type `number` but will be a string in the 2nd test case.
});