Try   HackMD

測試的作用域


  • describe 與 test 的執行優先順序:

    👉 decribe 比 test 早執行,且執行方向為由上往下。

    以官方的範例程式碼進行觀察:

    • describe 數量:總體結構上是最外層的 describe (describe outer) 作用域,內層包覆兩個 describe (describe inner 1 | describe inner 2)
    • test 數量共計三個,位置及上下順序分別於:
      • test 1 :describe inner 1 內層
      • test 2:describe outer 內
      • test 3 :describe inner 2 內層
    ​​​​describe('describe outer', () => {
    ​​​​  console.log('describe outer-a');
    
    ​​​​  describe('describe inner 1', () => {
    ​​​​    console.log('describe inner 1');
    
    ​​​​    test('test 1', () => console.log('test 1'));
    ​​​​  });
    
    ​​​​  console.log('describe outer-b');
    
    ​​​​  test('test 2', () => console.log('test 2'));
    
    ​​​​  describe('describe inner 2', () => {
    ​​​​    console.log('describe inner 2');
    
    ​​​​    test('test 3', () => console.log('test 3'));
    ​​​​  });
    
    ​​​​  console.log('describe outer-c');
    ​​​​});
    

最後觀察其印出的成果:

// describe outer-a
// describe inner 1
// describe outer-b
// describe inner 2
// describe outer-c
// test 1
// test 2
// test 3

describe 會比 test 早執行,且印出的順序是依序由上往下


  • Jest 提供的生命週期:

    • beforeAll(fn, timeout) :在該區域最一開始執行一次
    • beforeEach(fn , timeout):在該區域每個測試運行前值一次
    • afterEach(fn, timeout):在該區域每個測試執行完時都執行一次
    • afterAll(fn, timeout):在該區域所有測試都執行完後運行一次

describe 與 test 與生命週期的執行順序:

最後來拆解官方程式碼進行執行順序的觀察:

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
  • 單獨以全域情況下來看執行順序會是:beforeAll > beforeEach > test > afterEach > afterAll,而 beforeAll 、 afterAll 只會在最初及最後個別調用一次。
  • 當全域與區域都有執行 beforeEach 時全域會比區域的更早調用
  • 當全域與區域都有執行 afterEach 時區域會比全域的更早調用

瞭解測試的作用域之後,能更幫助在撰寫測試時的思考思路!!


參考文章
https://jestjs.io/docs/setup-teardown
https://jestjs.io/docs/27.x/api#beforeeachfn-timeout
https://medium.com/enjoy-life-enjoy-coding/unit-test-替測試設置分類-describe-及作用域-scoping-2c5082266ca
https://shawnlin0201.github.io/Jest.js/Jest-004-setup-teardown/
https://ithelp.ithome.com.tw/articles/10222357