Jest beforeEachとbeforeAllの違い

19672 ワード

 


テストを書くときは、テストを行う前に準備をしたり、テストを行った後に整理作業をしたりすることがよくあります.Jestはこの問題を処理するために補助関数を提供する.
複数回のテストのために繰り返し設定する作業がある場合は、beforeEachとafterEachを使用します.
各テストの前にメソッドinitializeCityDatabase()を呼び出し、各テストの後にメソッドclearCityDatabase()を呼び出す必要があります.
beforeEach(() => { initializeCityDatabase(); }); afterEach(() => { clearCityDatabase(); }); test('city database has Vienna', () => { expect(isCity('Vienna')).toBeTruthy(); }); test('city database has San Juan', () => { expect(isCity('San Juan')).toBeTruthy(); }); 

一度に設定する場合は、ファイルの先頭に一度だけ設定する必要があります.この設定が非同期動作の場合、1行で処理することはできません.JestはbeforeAllとafterAllがこのような状況を処理することを提供した.
beforeAll(() => { return initializeCityDatabase(); }); afterAll(() => { return clearCityDatabase(); }); test('city database has Vienna', () => { expect(isCity('Vienna')).toBeTruthy(); }); test('city database has San Juan', () => { expect(isCity('San Juan')).toBeTruthy(); }); 

役割ドメインのデフォルトでは、beforeとafterのブロックをファイル内の各テストに適用できます.さらにdescribeブロックによって、テスト中のブロックをグループ化することができる.beforeおよびafterのブロックがdescribeブロックの内部にある場合、describeブロック内のテストにのみ適用されます.
例えば、都市のデータベースだけでなく、食品のデータベースもあります.異なるテストのために異なる設定を行うことができます.
// Applies to all tests in this file
beforeEach(() => { return initializeCityDatabase(); }); test('city database has Vienna', () => { expect(isCity('Vienna')).toBeTruthy(); }); test('city database has San Juan', () => { expect(isCity('San Juan')).toBeTruthy(); }); describe('matching cities to foods', () => { // Applies only to tests in this describe block beforeEach(() => { return initializeFoodDatabase(); }); test('Vienna <3 sausage', () => { expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true); }); test('San Juan <3 plantains', () => { expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true); }); }); 

注意:最上位のbeforeEachはブロック内のbeforeEachを記述する前に実行され、以下の例は実行の順序を認識するのに便利である.
beforeAll(() => console.log('1 - beforeAll')); afterAll(() => console.log('1 - afterAll')); beforeEach(() => console.log('1 - beforeEach')); afterEach(() => console.log('1 - afterEach')); test('', () => console.log('1 - test')); describe('Scoped / Nested block', () => { beforeAll(() => console.log('2 - beforeAll')); afterAll(() => console.log('2 - afterAll')); beforeEach(() => console.log('2 - beforeEach')); afterEach(() => console.log('2 - afterEach')); test('', () => console.log('2 - test')); }); // 1 - beforeAll // 1 - beforeEach // 1 - test // 1 - afterEach // 2 - beforeAll // 1 - beforeEach //  // 2 - beforeEach // 2 - test // 2 - afterEach // 1 - afterEach // 2 - afterAll // 1 - afterAll