メインコンテンツへスキップ
Version: Next

全体

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

info

このページの TypeScript の例は、次のように Jest の API を明示的にインポートした場合にのみ動作します。

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

TypeScript で Jest をセットアップする方法の詳細については、Getting Started ガイドを参照してください。

メソッド


リファレンス

afterAll(fn, timeout)

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

オプションとして、timeout (ミリ秒) を指定して、中断前にどのくらい待機するかを指定することができます。 The default timeout is 5 seconds.

例:

例:

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関数 が describeブロック内に記述された場合は、 そのブロックの最後にafterAll関数が実行されます。

全テスト完了後ではなく、個々のテストの完了後にクリーンアップ処理を行いたい場合は、 afterEach 関数を使用して下さい。

異なるテストデータを使用して特定のテストのみを実行する場合は、 test.only.each を使用してください。

afterEach(fn, timeout)

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

オプションとして、timeout (ミリ秒) を指定して、中断前にどのくらい待機するかを指定することができます。 The default timeout is 5 seconds.

例:

例:

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 関数が describe ブロック内に記述された場合は、 afterEach 関数が記述されたブロックのみ、最後に実行されます。

全テストが完了した後に一度だけ何らかのクリーンアップを実行する場合は、 afterAll 関数を使用して下さい。

全テストが完了した後に一度だけ何らかのクリーンアップを実行する場合は、 afterAll 関数を使用して下さい。

beforeAll(fn, timeout)

このファイルの各テストが実行される前に、関数を実行します。 関数がpromiseを返す、またはジェネレータ関数の場合、Jestはテストを実行する前にpromiseが解決されるのを待ちます。

オプションとして、timeout (ミリ秒) を指定して、中断前にどのくらい待機するかを指定することができます。 The default timeout is 5 seconds.

例:

例:

const globalDatabase = makeGlobalDatabase();

beforeAll(() => {
// データベースをクリアし、テストデータを追加します。
// 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);
});
});

この例ではbeforeAll はテスト開始前に必ずデータベースのセットアップを行います。 セットアップが同期処理の場合は、 beforeAllを使用する必要はありません。 この関数の要点はJestがPromiseの状態が決まるまで待つことであり、非同期処理によるセットアップが行えるということであるとも言えます。

全テスト開始前ではなく、個々のテストの開始前に何らかの処理を行いたい場合は、 beforeEach 関数を使用して下さい。

beforeAll関数 が describeブロック内に記述された場合は、 そのブロックの最初に beforeAll関数が実行されます。

beforeEach(fn, timeout)

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

オプションとして、timeout (ミリ秒) を指定して、中断前にどのくらい待機するかを指定することができます。 The default timeout is 5 seconds.

例:

例:

const globalDatabase = makeGlobalDatabase();

beforeEach(() => {
// データベースをクリアし、テストデータを追加します。
// 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ブロック内に記述された場合は、 各ブロックの最初に beforeEach関数が実行されます。

何らかのセットアップ コードを 一度だけ実行したい場合は、 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();
});
});

これは必須ではありません - テスト ブロックをトップレベルに直接書き込むことができます。 しかしテストをグループにまとめたい場合には便利です。

テストに階層構造を持たせたい場合でも 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によりテストスイートを1回だけ記述し、データを渡すことができます。

例:

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

  • table: `` 各列ごとにfnに引数として渡される配列の配列です。 If you pass in a 1D array of primitives, internally it will be mapped to a table i.e. [1, 2, 3] -> [[1], [2], [3]].

  • name: `` テストスイートのタイトルとなる文字列

    • printf の書式に従うパラメータを注入することで、ユニークなテストタイトルを生成します。 :
      • %p - pretty-format.
      • %s- String.
      • %d- Number.
      • %i - Integer.
      • %f - Floating point value.
      • %j - JSON.
      • %o - Object.
      • %# - テストケースのインデックス。
      • %% - single percent sign ('%'). This does not consume an argument.
    • Or generate unique test titles by injecting properties of test case object with $variable
      • ネストされたオブジェクトの値を注入するには、keyPath 、すなわち $variable.path.to.value の形式で指定できます。
      • You can use $# to inject the index of the test case
      • You cannot use $variable with the printf formatting except for %%
  • fn: Function the suite of tests to be run, this is the function that will receive the parameters in each row as function arguments.

  • オプションとして、timeout (ミリ秒) を指定して、中断前に各行でどのくらい待機するかを指定することができます。 The default timeout is 5 seconds.

例:

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: タグによるテンプレートリテラル
    • | で区切られた変数名を表す1番目の行
    • ${value} 構文によるテンプレートリテラル式として提供される1行以上の後続のデータ。
  • name: String the title of the test suite, use $variable to inject test data into the suite title from the tagged template expressions, and $# for the index of the row.
    • ネストされたオブジェクトの値を注入するには、keyPath 、すなわち $variable.path.to.value の形式で指定できます。
  • fn: Function the suite of tests to be run, this is the function that will receive the test data object.
  • オプションとして、timeout (ミリ秒) を指定して、中断前に各行でどのくらい待機するかを指定することができます。 The default timeout is 5 seconds.

例:

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)

1つのdescribeブロックだけを実行したい場合には describe.onlyを使用して下さい:

次のエイリアスでも使用可能です: fdescribe.each(table)(name, fn)fdescribe.each`table`(name, fn)

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)

データ駆動型テストで特定のテストスイートのみを実行する場合は、 describe.only.each を使用してください。

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

次の別名でも同様となります: xdescribe(name, fn)

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)

特定のdescribeブロックを実行したくない場合には describe.skip を使用して下さい。

You can use describe.skip if you do not want to run the tests of a particular describe block:

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
});

次のエイリアスでも使用可能です: xdescribe.each(table)(name, fn)xdescribe.each`table`(name, fn) Beware that the describe block will still run. If you have some setup that also should be skipped, do it in a beforeAll or beforeEach block.

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

次の別名でも同様となります: xdescribe.each(table)(name, fn)and 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番目の引数 (任意) は タイムアウト値 (ミリ秒単位) で、中止するまでの待ち時間を指定します。 The default timeout is 5 seconds.

If a promise is returned from test, Jest will wait for the promise to resolve before letting the test complete. 例えば、 lemonを含むリストを取得することを期待されるPromise関数を返すfetchBeverageList() 関数があったとします。 以下のコードでテストできます:

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

Even though the call to test will return right away, the test doesn't complete until the promise resolves. For more details, see Testing Asynchronous Code page.

tip

Jest は、通常は done と呼ばれるテスト関数に引数を与えた場合にも待ちます。 This could be handy when you want to test callbacks.

test.concurrent(name, fn, timeout)

次の別名でも同様となります: it.concurrent(name, fn, timeout)

caution

test.concurrent is considered experimental - see here for details on missing features and other issues.

test.concurrentはテストを並列に実行する場合に使用します。

第1引数にテスト名を、第2引数にテストの確認項目を含む関数を設定します。 3番目の引数 (任意) は タイムアウト値 (ミリ秒単位) で、中止するまでの待ち時間を指定します。 The default timeout is 5 seconds.

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

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

Use the maxConcurrency configuration option to prevent Jest from executing more than the specified amount of tests at the same time.

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

次の別名でも同様となります: it.concurrent.each(table)(name, fn, timeout)

異なるテストデータで同じ内容のテストを行う場合は、test.concurrent.eachを使用します。 test.each によりテストを1回だけ記述し、データを渡すことができます。

例:

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

  • table: `` テストに渡される配列の配列です。 If you pass in a 1D array of primitives, internally it will be mapped to a table i.e. [1, 2, 3] -> [[1], [2], [3]]
  • name: `` テストブロックのタイトルとなります。
    • printf の書式に従うパラメータを注入することで、ユニークなテストタイトルを生成します。 :
      • %p - pretty-format.
      • %s- String.
      • %d- Number.
      • %i - Integer.
      • %f - Floating point value.
      • %j - JSON.
      • %o - Object.
      • %# - テストケースのインデックス。
      • %% - single percent sign ('%'). This does not consume an argument.
  • fn: Function the test to be run, this is the function that will receive the parameters in each row as function arguments, this will have to be an asynchronous function.
  • オプションとして、timeout (ミリ秒) を指定して、中断前に各行でどのくらい待機するかを指定することができます。 The default timeout is 5 seconds.

例:

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: タグによるテンプレートリテラル
    • | で区切られた変数名を表す1番目の行
    • ${value} 構文によるテンプレートリテラル式として提供される1行以上の後続のデータ。
  • name: `` テストスイートのタイトルで、 タグによるテンプレート式からスイートのタイトルにテストデータを挿入するには$variable を使用してください。
    • ネストされたオブジェクトの値を注入するには、keyPath 、すなわち $variable.path.to.value の形式で指定できます。
  • fn: Function the test to be run, this is the function that will receive the test data object, this will have to be an asynchronous function.
  • オプションとして、timeout (ミリ秒) を指定して、中断前に各行でどのくらい待機するかを指定することができます。 The default timeout is 5 seconds.

例:

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)

Also under the alias: it.concurrent.only.each(table)(name, fn)

Use test.concurrent.only.each if you want to only run specific tests with different test data concurrently.

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)

Also under the alias: it.concurrent.skip.each(table)(name, fn)

Use test.concurrent.skip.each if you want to stop running a collection of asynchronous data driven tests.

次のエイリアスでも使用可能です: it.each(table)(name, fn)it.each`table`(name, fn)

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によりテストを1回だけ記述し、データを渡すことができます。

例:

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

  • table: `` テストに渡される配列の配列です。 If you pass in a 1D array of primitives, internally it will be mapped to a table i.e. [1, 2, 3] -> [[1], [2], [3]]
  • name: `` テストブロックのタイトルとなります。
    • printf の書式に従うパラメータを注入することで、ユニークなテストタイトルを生成します。 :
      • %p - pretty-format.
      • %s- String.
      • %d- Number.
      • %i - Integer.
      • %f - Floating point value.
      • %j - JSON.
      • %o - Object.
      • %# - テストケースのインデックス。
      • %% - single percent sign ('%'). This does not consume an argument.
    • Or generate unique test titles by injecting properties of test case object with $variable
      • ネストされたオブジェクトの値を注入するには、keyPath 、すなわち $variable.path.to.value の形式で指定できます。
      • You can use $# to inject the index of the test case
      • You cannot use $variable with the printf formatting except for %%
  • fn: Function the test to be run, this is the function that will receive the parameters in each row as function arguments.
  • オプションとして、timeout (ミリ秒) を指定して、中断前に各行でどのくらい待機するかを指定することができます。 The default timeout is 5 seconds.

例:

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: タグによるテンプレートリテラル
    • | で区切られた変数名を表す1番目の行
    • ${value} 構文によるテンプレートリテラル式として提供される1行以上の後続のデータ。
  • name: `` テストスイートのタイトルで、 タグによるテンプレート式からスイートのタイトルにテストデータを挿入するには$variable を使用してください。
    • ネストされたオブジェクトの値を注入するには、keyPath 、すなわち $variable.path.to.value の形式で指定できます。
  • fn: Function the test to be run, this is the function that will receive the test data object.
  • オプションとして、timeout (ミリ秒) を指定して、中断前に各行でどのくらい待機するかを指定することができます。 The default timeout is 5 seconds.

例:

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)

Also under the alias: it.failing(name, fn, timeout)

note

This is only available with the default jest-circus runner.

Use test.failing when you are writing a test and expecting it to fail. These tests will behave the other way normal tests do. If failing test will throw any errors then it will pass. If it does not throw it will fail.

tip

You can use this type of test i.e. when writing code in a BDD way. In that case the tests will not show up as failing until they pass. Then you can just remove the failing modifier to make them pass.

It can also be a nice way to contribute failing tests to a project, even if you don't know how to fix the bug.

例:

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)

Also under the alias: it.failing.each(table)(name, fn) and it.failing.each`table`(name, fn)

note

This is only available with the default jest-circus runner.

You can also run multiple tests at once by adding each after failing.

例:

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)

Also under the aliases: it.only.failing(name, fn, timeout), fit.failing(name, fn, timeout)

note

This is only available with the default jest-circus runner.

Use test.only.failing if you want to only run a specific failing test.

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

Also under the aliases: it.skip.failing(name, fn, timeout), xit.failing(name, fn, timeout), xtest.failing(name, fn, timeout)

note

This is only available with the default jest-circus runner.

Use test.skip.failing if you want to skip running a specific failing test.

test.only(name, fn, timeout)

次の別名でも同様です: it.only(name, fn, timeout)fit(name, fn, timeout)

大きなテストファイルをデバッグする時、テストの一部だけを実行したいことがあるでしょう。 .only を使用すると、テストファイルの中で実行したいテストだけを行うことができます。

オプションとして、timeout (ミリ秒) を指定して、中断前にどのくらい待機するかを指定することができます。 The default timeout is 5 seconds.

test.only で実行されるので、"It is raining" テストのみがそのテストファイルで実行されます。

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)

Also under the aliases: it.only.each(table)(name, fn), fit.each(table)(name, fn), it.only.each`table`(name, fn) and fit.each`table`(name, fn)

test.only.each は 2 つの API で利用できます:

次の別名でも同様です: it.skip(name, fn) または xit(name, fn) または xtest(name, fn)

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.only で実行されるので、"It is raining" テストのみがそのテストファイルで実行されます。

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

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

単純ににテストをコメントアウトすることもできますが、テストが存在することとシンタックスハイライトを維持できるため、 test.skipを利用したほうが良いことがしばしばあります。

次のエイリアスでも使用可能です: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(table)(name, fn)

一連のデータ駆動型テストを停止したい場合は、 test.skip.each を使用してください。

test.skip.each は 2 つの API で利用できます:

次の別名でも使用可能です: it.todo(name)

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');
tip

test.todo will throw an error if you pass it a test callback function. Use test.skip instead, if you already implemented the test, but do not want it to run.

TypeScript Usage

info

このページの TypeScript の例は、次のように Jest の API を明示的にインポートした場合にのみ動作します。

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

TypeScript で Jest をセットアップする方法の詳細については、Getting Started ガイドを参照してください。

.each

The .each modifier offers few different ways to define a table of the test cases. Some of the APIs have caveats related with the type inference of the arguments which are passed to describe or test callback functions. Let's take a look at each of them.

note

For simplicity test.each is picked for the examples, but the type inference is identical in all cases where .each modifier can be used: describe.each, test.concurrent.only.each, test.skip.each, etc.

Array of objects

The array of objects API is most verbose, but it makes the type inference a painless task. A table can be inlined:

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`
});

Or declared separately as a variable:

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`
});

Array of arrays

The array of arrays style will work smoothly with inlined tables:

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`
});

However, if a table is declared as a separate variable, it must be typed as an array of tuples for correct type inference (this is not needed only if all elements of a row are of the same type):

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`
});

Template literal

If all input values are of the same type, the template literal API will type the arguments correctly:

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`
});

If the inputs have different types, the arguments will be typed as a union of all the input types (i.e. type of the variables inside the template literal):

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`
});

Otherwise, if you want each argument to have the right type, you have to explicitly provide the generic type argument:

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`
});
caution

Keep in mind the variables inside the template literal are not type checked, so you have to ensure that their types are correct.

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.
});