メインコンテンツへスキップ
Version: 25.x

全体

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

メソッド


リファレンス

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

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

  • table: タグによるテンプレートリテラル
    • | で区切られた変数名を表す1番目の行
    • ${value} 構文によるテンプレートリテラル式として提供される1行以上の後続のデータ。
  • name: ` テストスイートのタイトルで、 タグによるテンプレート式からスイートのタイトルにテストデータを挿入するには$variable` を使用してください。
    • ネストされたオブジェクトの値を注入するには、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.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.
  • 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);
});

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.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.