Globals
テストファイルでは、Jest はそれぞれのメソッドとオブジェクトをグローバル環境に配置します。 それらを使用するために require または import する必要はありません。 ただし、明示的にインポートしたい場合は、 '@jest/globals' から {describe, expect, test} をインポートすることができます。
メソッド
afterAll(fn, timeout)afterEach(fn, timeout)beforeAll(fn, timeout)beforeEach(fn, timeout)describe(name, fn)describe.each(table)(name, fn, timeout)describe.only(name, fn)describe.only.each(table)(name, fn)describe.skip(name, fn)describe.skip.each(table)(name, fn)test(name, fn, timeout)test.each(table)(name, fn, timeout)test.only(name, fn, timeout)test.only.each(table)(name, fn)test.skip(name, fn)test.skip.each(table)(name, fn)test.todo(name)
リファレンス
afterAll(fn, timeout)
このファイル内のすべてのテストが完了した後に、関数を実行します。 関数がpromiseまたはジェネレータを返した場合、Jestはそのpromiseが解決されるのを待ちます。
異常終了するまでの待ち時間を指定する 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 を必ず実行します。
afterAll関数 が describeブロック内に記述された場合は、 そのブロックの最後にafterAll関数が実行されます。
全テスト完了後ではなく、個々のテストの完了後にクリーンアップ処理を行いたい場合は、 afterEach 関数を使用して下さい。
afterEach(fn, timeout)
このファイル内の各テストが完了するたびに、関数を実行します。 関数がpromiseまたはジェネレータを返した場合、Jestはそのpromiseが解決されるのを待ちます。
異常終了するまでの待ち時間を指定する 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 を必ず実行します。
afterEach 関数が describe ブロック内に記述された場合は、 afterEach 関数が記述されたブロックのみ、最後に実行されます。
全テストが完了した後に一度だけ何らかのクリーンアップを実行する場合は、 afterAll 関数を使用して下さい。
beforeAll(fn, timeout)
このファイルのいずれかのテストを実行する前に、関数を実行します。 関数がpromiseまたはジェネレータを返した場合、Jestはテストを実行する前にpromiseが解決されるのを待ちます。
異常終了するまでの待ち時間を指定する 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がPromiseの状態が決まるまで待つことであり、非同期処理によるセットアップが行えるということであるとも言えます。
beforeAll関数 が describeブロック内に記述された場合は、 そのブロックの最初に beforeAll関数が実行されます。
全テスト開始前ではなく、個々のテストの開始前に何らかの処理を行いたい場合は、 beforeEach 関数を使用して下さい。
beforeEach(fn, timeout)
ファイルの各テストが実行される前に、関数を実行します。 関数がpromiseまたはジェネレータを返した場合、Jestはテストを実行する前にpromiseが解決されるのを待ちます。
異常終了するまでの待ち時間を指定する 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 関数は個々のテストを開始する前に必ずデータベースのリセットを行います。
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();
});
});
これは必須ではありません - 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')).toThrowError(CustomError);
});
test('with extra whitespace throws CustomError', () =>; {
expect(() =>; binaryStringToNumber(' 100')).toThrowError(CustomError);
});
});
describe.each(table)(name, fn, timeout)
同じテストスイートを異なるデータで複製し続ける場合は、 describe.each を使用します。 describe.each では、テストスイートを一度作成するだけで、データを渡すことができます。
describe.each は 2 つの API で利用できます:
1. describe.each(table)(name, fn, timeout)
table:Arrayof Arrays with the arguments that are passed into thefnfor each row.- 注意: 1次元の配列を渡した場合には、内部的には
[1, 2, 3] -> [[1], [2], [3]]のようにテーブルにマッピングされます
- 注意: 1次元の配列を渡した場合には、内部的には
name:Stringthe title of the test suite.- Generate unique test titles by positionally injecting parameters with
printfformatting:%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.
- Generate unique test titles by positionally injecting parameters with
fn:実行されるテストの一連の関数。各行のパラメータを引数として受け取る関数です。- 各行での異常終了するまでの待ち時間を指定する
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);
});
});
2. describe.each`table`(name, fn, timeout)
table:Tagged Template Literal|で区切られた変数名を表す1番目の行${value}構文によるテンプレートリテラル式として提供される1行以上の後続のデータ。
name:Stringthe title of the test suite, use$variableto inject test data into the suite title from the tagged template expressions.- ネストされたオブジェクトの値を注入するには、keyPath 、すなわち
$variable.path.to.valueの形式で指定できます。
- ネストされたオブジェクトの値を注入するには、keyPath 、すなわち
fn:実行される一連のテスト関数で、テストデータのオブジェクトを受け取ります。- 各行での異常終了するまでの待ち時間を指定する
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)
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 ran', () => {
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 $b', ({a, b, expected}) => {
test('passes', () => {
expect(a + b).toBe(expected);
});
});
test('will not be ran', () => {
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.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 ran
});
});
test('will be ran', () => {
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 $b', ({a, b, expected}) => {
test('will not be ran', () => {
expect(a + b).toBe(expected); // will not be ran
});
});
test('will be ran', () => {
expect(1 / 0).toBe(Infinity);
});
test(name, fn, timeout)
次の別名でも同様となります: it(name, fn, timeout)
テストファイルに必要なのは、テストを実行する test メソッドだけです。 例えば、0でなければならない関数 inchesOfRain() があるとしましょう。 テストは以下のように書けます:
test('did not rain', () => {
expect(inchesOfRain()).toBe(0);
});
第1引数にテスト名を、第2引数にテストの確認項目を含む関数を設定します。 3番目の引数 (任意) は タイムアウト値 (ミリ秒単位) で、中止するまでの待ち時間を指定します。 注意: デフォルトのタイムアウトは5秒です。
注意:
testからPromiseが返された場合、Jestはテストが完了する前にPromiseの状態が決まるまで待ちます。 Jest は、通常はdoneと呼ばれるテスト関数に引数を与えた場合にも待ちます。 この動作はコールバックをテストしたい場合に便利です。 非同期なコードをテストする方法をこちらを参照してください。
例えば、 lemonを含むリストを取得することを期待されるPromise関数を返すfetchBeverageList() 関数があったとします。 以下のコードでテストできます:
test('has lemon in it', () => {
return fetchBeverageList().then(list => {
expect(list).toContain('lemon');
});
});
たとえtestブロックが直ちに値を返したとしても、テストはPromiseの状態が決まるまでは終了しません。
test.each(table)(name, fn, timeout)
次のエイリアスでも使用可能です: it.each(table)(name, fn) と it.each`table`(name, fn)
Use test.each if you keep duplicating the same test with different data. test.each allows you to write the test once and pass data in.
test.each は 2 つの API で利用できます:
1. test.each(table)(name, fn, timeout)
table:Arrayof Arrays with the arguments that are passed into the testfnfor each row.- 注意: 1次元の配列を渡した場合には、内部的には
[1, 2, 3] -> [[1], [2], [3]]のようにテーブルにマッピングされます
- 注意: 1次元の配列を渡した場合には、内部的には
name:Stringthe title of the test block.- Generate unique test titles by positionally injecting parameters with
printfformatting:%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.
- Generate unique test titles by positionally injecting parameters with
fn:テストを実行する関数で、各行のパラメータを関数の引数として受け取ります。- 各行での異常終了するまでの待ち時間を指定する
timeoutオプション(ミリ秒単位)を指定できます。 注意: デフォルトのタイムアウトは5秒です。
例:
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:Tagged Template Literal|で区切られた変数名を表す1番目の行${value}構文によるテンプレートリテラル式として提供される1行以上の後続のデータ。
name:Stringthe title of the test, use$variableto inject test data into the test title from the tagged template expressions.- ネストされたオブジェクトの値を注入するには、keyPath 、すなわち
$variable.path.to.valueの形式で指定できます。
- ネストされたオブジェクトの値を注入するには、keyPath 、すなわち
fn:テストを実行する関数で、 テストデータのオブジェクトを受け取ります。- 各行での異常終了するまでの待ち時間を指定する
timeoutオプション(ミリ秒単位)を指定できます。 注意: デフォルトのタイムアウトは5秒です。
例:
test.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added $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 オプション(ミリ秒単位) を指定できます。 注意: デフォルトのタイムアウトは5秒です。
例えば、次のようなテストがあったとしましょう:
test.only('it is raining', () => {
expect(inchesOfRain()).toBeGreaterThan(0);
});
test('it is not snowing', () => {
expect(inchesOfSnow()).toBe(0);
});
test.only で実行されるので、"It is raining" テストのみがそのテストファイルで実行されます。
通常はテストの動作を管理する手段として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 を使用してください。
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 ran', () => {
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 $b', ({a, b, expected}) => {
expect(a + b).toBe(expected);
});
test('will not be ran', () => {
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があるので、"it is raining"のテストだけが実行されます。
単純ににテストをコメントアウトすることもできますが、テストが存在することとシンタックスハイライトを維持できるため、 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 ran
});
test('will be ran', () => {
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 $b', ({a, b, expected}) => {
expect(a + b).toBe(expected); // will not be ran
});
test('will be ran', () => {
expect(1 / 0).toBe(Infinity);
});
test.todo(name)
次の別名でも使用可能です: it.todo(name)
Use test.todo when you are planning on writing tests. These tests will be highlighted in the summary output at the end so you know how many tests you still need todo.
Note: If you supply a test callback function then the test.todo will throw an error. If you have already implemented the test and it is broken and you do not want it to run, then use test.skip instead.
API
name: テスト計画のタイトルの文字列。
例:
const add = (a, b) => a + b;
test.todo('add should be associative');