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

グローバル

テストファイルでは、Jestはこれらのメソッドとオブジェクトをグローバル環境に配置します。これらを使用するために、何もrequireまたはimportする必要はありません。ただし、明示的なimportを好む場合は、`import {describe, expect, test} from '@jest/globals'`を実行できます。

情報

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

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

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

メソッド


参照

afterAll(fn, timeout)

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

必要に応じて、タイムアウト(ミリ秒単位)を指定して、中止するまでの待機時間を指定できます。デフォルトのタイムアウトは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`が呼び出されることを保証します。

`afterAll`が`describe`ブロック内にある場合、`describe`ブロックの最後に実行されます。

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

afterEach(fn, timeout)

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

必要に応じて、タイムアウト(ミリ秒単位)を指定して、中止するまでの待機時間を指定できます。デフォルトのタイムアウトは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`が呼び出されることを保証します。

`afterEach`が`describe`ブロック内にある場合、この`describe`ブロック内にあるテストの後でのみ実行されます。

すべてのテストが実行された後、一度だけクリーンアップを実行する場合は、代わりに`afterAll`を使用します。

beforeAll(fn, timeout)

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

必要に応じて、タイムアウト(ミリ秒単位)を指定して、中止するまでの待機時間を指定できます。デフォルトのタイムアウトは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がPromiseが解決されるのを待つことです。そのため、非同期セットアップも可能です。

`beforeAll`が`describe`ブロック内にある場合、`describe`ブロックの最初に実行されます。

テストの実行前にではなく、各テストの前に何かを実行する場合は、代わりに`beforeEach`を使用します。

beforeEach(fn, timeout)

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

必要に応じて、タイムアウト(ミリ秒単位)を指定して、中止するまでの待機時間を指定できます。デフォルトのタイムアウトは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`は、各テストに対してデータベースがリセットされることを保証します。

`beforeEach`が`describe`ブロック内にある場合、`describe`ブロック内の各テストに対して実行されます。

テストの実行前に一度だけセットアップコードを実行する必要がある場合は、代わりに`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: 各行の`fn`に渡される引数を含む配列の配列。プリミティブの1次元配列を渡すと、内部的にテーブルにマップされます(例:`[1, 2, 3] -> [[1], [2], [3]]`)。

  • name: テストスイートのタイトルを表す文字列。

    • `printf`フォーマットを使用して、位置的にパラメーターを挿入することで、一意のテストタイトルを生成します。
      • %p - pretty-format.
      • %s- 文字列。
      • %d- 数値。
      • %i - 整数。
      • %f - 浮動小数点数値。
      • %j - JSON。
      • %o - オブジェクト。
      • %# - テストケースのインデックス。
      • %% - 単一のパーセント記号 ('%')。これは引数を消費しません。
    • または、`$variable`を使用してテストケースオブジェクトのプロパティを挿入することで、一意のテストタイトルを生成します。
      • ネストされたオブジェクトの値を挿入するには、キーパスを指定できます(例:`$variable.path.to.value`)。
      • `$#`を使用して、テストケースのインデックスを挿入できます。
      • `%%`を除き、`$variable`を`printf`フォーマットと共に使用することはできません。
  • fn: 実行されるテストスイートを表す関数。これは、各行のパラメーターを関数引数として受け取る関数です。

  • 必要に応じて、タイムアウト(ミリ秒単位)を指定して、各行の処理を中止するまでの待機時間を指定できます。デフォルトのタイムアウトは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: テンプレートリテラル。
    • `|`で区切られた変数名の列見出しの最初の行。
    • `${value}`構文を使用してテンプレートリテラル式として提供される1つ以上の後続のデータ行。
  • name: テストスイートのタイトルを表す文字列。テンプレートリテラル式からテストデータをスイートタイトルに挿入するには`$variable`を使用し、行のインデックスには`$#`を使用します。
    • ネストされたオブジェクトの値を挿入するには、キーパスを指定できます(例:`$variable.path.to.value`)。
  • fn: 実行されるテストスイートを表す関数。これは、テストデータオブジェクトを受け取る関数です。
  • 必要に応じて、タイムアウト(ミリ秒単位)を指定して、各行の処理を中止するまでの待機時間を指定できます。デフォルトのタイムアウトは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)`

1つの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ブロック自体は実行されることに注意してください。スキップする必要がある設定がある場合は、beforeAllまたはbeforeEachブロックで行ってください。

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メソッドだけです。たとえば、0になるはずの関数inchesOfRain()があるとします。テスト全体は次のようになります。

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

最初の引数はテスト名、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);
});
ヒント

Jestが同時に実行するテスト数を指定の上限を超えないようにするには、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に各行に対して渡される引数を含む、配列の配列。プリミティブの1次元配列を渡すと、内部的にテーブルにマップされます(例:[1, 2, 3] -> [[1], [2], [3]])。
  • name:テストブロックのタイトルを表す文字列。
    • `printf`フォーマットを使用して、位置的にパラメーターを挿入することで、一意のテストタイトルを生成します。
      • %p - pretty-format.
      • %s- 文字列。
      • %d- 数値。
      • %i - 整数。
      • %f - 浮動小数点数値。
      • %j - JSON。
      • %o - オブジェクト。
      • %# - テストケースのインデックス。
      • %% - 単一のパーセント記号 ('%')。これは引数を消費しません。
  • fn:実行するテストを表す関数。これは、各行のパラメータを関数引数として受け取る関数であり、**非同期関数である必要があります**。
  • 必要に応じて、タイムアウト(ミリ秒単位)を指定して、各行の処理を中止するまでの待機時間を指定できます。デフォルトのタイムアウトは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: テンプレートリテラル。
    • `|`で区切られた変数名の列見出しの最初の行。
    • `${value}`構文を使用してテンプレートリテラル式として提供される1つ以上の後続のデータ行。
  • name:テストのタイトルを表す文字列。タグ付きテンプレート式からテストデータにタイトルを挿入するには、$variableを使用します。
    • ネストされたオブジェクトの値を挿入するには、キーパスを指定できます(例:`$variable.path.to.value`)。
  • fn:実行するテストを表す関数。これは、テストデータオブジェクトを受け取る関数であり、**非同期関数である必要があります**。
  • 必要に応じて、タイムアウト(ミリ秒単位)を指定して、各行の処理を中止するまでの待機時間を指定できます。デフォルトのタイムアウトは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に各行に対して渡される引数を含む、配列の配列。プリミティブの1次元配列を渡すと、内部的にテーブルにマップされます(例:[1, 2, 3] -> [[1], [2], [3]])。
  • name:テストブロックのタイトルを表す文字列。
    • `printf`フォーマットを使用して、位置的にパラメーターを挿入することで、一意のテストタイトルを生成します。
      • %p - pretty-format.
      • %s- 文字列。
      • %d- 数値。
      • %i - 整数。
      • %f - 浮動小数点数値。
      • %j - JSON。
      • %o - オブジェクト。
      • %# - テストケースのインデックス。
      • %% - 単一のパーセント記号 ('%')。これは引数を消費しません。
    • または、`$variable`を使用してテストケースオブジェクトのプロパティを挿入することで、一意のテストタイトルを生成します。
      • ネストされたオブジェクトの値を挿入するには、キーパスを指定できます(例:`$variable.path.to.value`)。
      • `$#`を使用して、テストケースのインデックスを挿入できます。
      • `%%`を除き、`$variable`を`printf`フォーマットと共に使用することはできません。
  • fn:実行するテストを表す関数。これは、各行のパラメータを関数引数として受け取る関数です。
  • 必要に応じて、タイムアウト(ミリ秒単位)を指定して、各行の処理を中止するまでの待機時間を指定できます。デフォルトのタイムアウトは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: テンプレートリテラル。
    • `|`で区切られた変数名の列見出しの最初の行。
    • `${value}`構文を使用してテンプレートリテラル式として提供される1つ以上の後続のデータ行。
  • name:テストのタイトルを表す文字列。タグ付きテンプレート式からテストデータにタイトルを挿入するには、$variableを使用します。
    • ネストされたオブジェクトの値を挿入するには、キーパスを指定できます(例:`$variable.path.to.value`)。
  • fn:実行するテストを表す関数。これは、テストデータオブジェクトを受け取る関数です。
  • 必要に応じて、タイムアウト(ミリ秒単位)を指定して、各行の処理を中止するまでの待機時間を指定できます。デフォルトのタイムアウトは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ランナーでのみ使用できます。

`failing` の後に `each` を追加することで、複数のテストを一度に実行することもできます。

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` を使用して、そのテストファイルで実行するテストを指定できます。

必要に応じて、タイムアウト(ミリ秒単位)を指定して、中止するまでの待機時間を指定できます。デフォルトのタイムアウトは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 の使用方法

情報

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

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

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

.each

.each 修飾子は、テストケースのテーブルを定義するいくつかの異なる方法を提供します。一部のAPIには、`describe` または `test` コールバック関数に渡される引数の型推論に関連する注意点があります。それぞれを見てみましょう。

備考

簡潔にするため、例では `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', ({a, b, expected}) => {
// all arguments are of type `number`
});

それ以外の場合は、ジェネリック型引数が必要です。

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}) => {
// without the generic argument in this case types would default to `unknown`
});