1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JestHookの実行順序について

Posted at

■はじめに

最近、JestでUnitテストを書くことが多かったため、その中でよく使う「JestHook」の実行順序に関してログを残そうと思います。

■JestHookとは

テストを実行する前にセットアップをしたり、テストが終わったあとにクリーンアップしたりする場合があります。

その際に使えるのが「JestHook」です。

JestHookには

  • beforeEach
  • afterEach
  • beforeAll
  • afterAll

があります。

例えば、DBを用いたテストを実施するには、テストを実行前にデータベースと接続して、テストに必要なデータの準備を行う必要があります。

他にも、new Date()などテストを実行するタイミングで動的に変わる値を固定するなども、テスト実行前に実施する必要があります。

また、テスト終了後には、セットアップで行ったモックや、DBへ追加したデータが、他のテストに影響を与えないよう、元の状態に戻す必要があります。

これらの処理はテストで共通して実行するため、全てのテストで同じ処理を何度も書くのは効率が悪いです。

そこで、「JestHook」を用いて、共通化して行うことがあります。

■JestHookの実行順序

◆今回実行するテストコード

describe('外側のテスト', () => {
	beforeEach(() => {
		console.log('beforeEach - ①');
	});

	afterEach(() => {
		console.log('afterEach - ①');
	});

	beforeAll(() => {
		console.log('beforeAll - ①');
	});

	afterAll(() => {
		console.log('afterAll - ①');
	});

	it('テスト①', () => {
		console.log('テスト①の中身');
	});

	it('テスト②', () => {
		console.log('テスト②の中身');
	});

	describe('内側のテスト', () => {
		beforeEach(() => {
			console.log('beforeEach - ②');
		});

		afterEach(() => {
			console.log('afterEach - ②');
		});

		beforeAll(() => {
			console.log('beforeAll - ②');
		});

		afterAll(() => {
			console.log('afterAll - ②');
		});

		it('テスト③', () => {
			console.log('テスト③の中身');
		});

		it('テスト④', () => {
			console.log('テスト④の中身');
		});
	});
});

今回、検証で実行するテストコードは、こちらになります。

◆実行結果

beforeAll - 

beforeEach - 
テストの中身
afterEach - 

beforeEach - 
テストの中身
afterEach - 

beforeAll - 
beforeEach - 
beforeEach - 
テストの中身
afterEach - 
afterEach - 

beforeEach - 
beforeEach - 
テストの中身
afterEach - 
afterEach - 

afterAll - 
afterAll - 

実行結果はこの様になりました。

beforeAllafterAllは、全てのテストが実行される前と後で、1回だけ実行されている事がわかります。

beforeEachafterEachは、各テストが実行される前に、何度も実行されていることがわかります。

beforeEachは外側に書いたものから、内側に書いたものの順番で実行されています。

afterEachは内側に書いたものから、外側に書いたものの順番で実行されています。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?