Jest 異步代碼 測試要注意的點

Jest 異步代碼測試中,有一些點,我們記錄一下。

如果要測的是回調函數,那麼可以使用done 函數。

官網是如下解釋的:

Instead of putting the test in a function with an empty argument, use a single argument called done. Jest will wait until the done callback is called before finishing the test.

If done() is never called, the test will fail, which is what you want to happen.

test('the data is peanut butter', done => {
  function callback(data) {
    expect(data).toBe('peanut butter');
    done();
  }

  fetchData(callback);
});

好,下面要說的是如果要測的是Promise , 要測case 是成功時,只需使用then()就好,如果是要測失敗時,不僅要使用catch(),還建議添加expect.assertions。下面的測試用例中,測的是Promise 失敗時的例子,使用的是catch(),當Promise 成功時,那就執行不到return 語句,因此沒有assertions 行語句,這個測試用例就啥也沒做,就自然通過了。因此這時我們需要加上expect.assertions 行語句。

官網解釋:

If you expect a promise to be rejected use the .catch method. Make sure to add expect.assertions to verify that a certain number of assertions are called. Otherwise a fulfilled promise would not fail the test.

test('the fetch fails with an error', () => {
  expect.assertions(1);
  return fetchData().catch(e => expect(e).toMatch('error'));
});

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章