寫測試的時候,我們經常需要進行測試之前做一些准備工作,和在進行測試后需要進行一些整理工作。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(); });
一次性設置
在某些情況下,你只需要在文件的開頭做一次設置。這種設置是異步行為的時候,你不太可能一行處理它。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