15
10

More than 3 years have passed since last update.

【Jest入門】前後処理が呼び出されるタイミング~beforeEach、beforeAll、afterAll、afterEach~

Posted at

はじめに

Jestでテストを書いていて、DBのクリーンアップ処理やモックのリセットをする際に、beforeAllbeforeEachなどを使う機会がありました。改めて調べると、呼び出されるタイミングが特殊なものもあったのでまとめました。

調査

describe関数をネストする例で、beforeEach、beforeAll、afterAll、afterEachの実行タイミングを調べてみました。

timing.test.js
// 前後処理の実行されるタイミング
describe("テスト", () => {
  beforeAll(() => console.log("1 - beforeAll"));
  afterAll(() => console.log("1 - afterAll"));
  beforeEach(() => console.log("1 - beforeEach"));
  afterEach(() => console.log("1 - afterEach"));
  test("テスト1", () => console.log("1 - test")); //テスト1

  describe("ネストされたテスト", () => {
    beforeAll(() => console.log("2 - beforeAll"));
    afterAll(() => console.log("2 - afterAll"));
    beforeEach(() => console.log("2 - beforeEach"));
    afterEach(() => console.log("2 - afterEach"));
    test("テスト2", () => console.log("2 - test"));//テスト2
  });
});

結果

$ npm test jest-basic/src/timing.test.js

> jest-basic@1.0.0 test jest-basic
> jest "/Users/jest-basic/src/timing.test.js"

 PASS  src/timing.test.js
  テスト
    ✓ テスト1 (3 ms)
    ネストされたテスト
      ✓ テスト2 (3 ms)

  console.log
    1 - beforeAll

      at src/timing.test.js:3:27

  console.log
    1 - beforeEach

      at Object.<anonymous> (src/timing.test.js:5:28)

  console.log
    1 - test

      at Object.<anonymous> (src/timing.test.js:7:30)

  console.log
    1 - afterEach

      at Object.<anonymous> (src/timing.test.js:6:27)

  console.log
    2 - beforeAll

      at src/timing.test.js:10:29

  console.log
    1 - beforeEach

      at Object.<anonymous> (src/timing.test.js:5:28)

  console.log
    2 - beforeEach

      at Object.<anonymous> (src/timing.test.js:12:30)

  console.log
    2 - test

      at Object.<anonymous> (src/timing.test.js:14:32)

  console.log
    2 - afterEach

      at Object.<anonymous> (src/timing.test.js:13:29)

  console.log
    1 - afterEach

      at Object.<anonymous> (src/timing.test.js:6:27)

  console.log
    2 - afterAll

      at src/timing.test.js:11:28

  console.log
    1 - afterAll

      at src/timing.test.js:4:26

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        0.47 s, estimated 1 s
Ran all test suites matching

まとめ

  1. 1 - beforeAll
  2. 1 - beforeEach
  3. 1 - test
  4. 1 - afterEach
  5. 2 - beforeAll
  6. 1 - beforeEach ← 注意
  7. 2 - test
  8. 2 - afterEach
  9. 1 - afterEach ← 注意
  10. 2 - afterAll
  11. 1 - afterAll

ネストされたテストでは、外側のテストのbeforeEachafterEachが実行されていることが確認できました。beforeEach、beforeAll、afterAll、afterEachを使う際は、タイミングを意識したTestを書く必要がありますね。

15
10
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
15
10