簡體   English   中英

使用 nockjs 和 jest 進行承諾/異步單元測試的代碼覆蓋問題

[英]Code coverage concern on promise/asynchronous unit testing using nockjs and jest

我使用 NockJS 和 Jest 為反應應用程序編寫了一個簡單的 API 調用單元測試,如下所示:

AjaxService.js

export const AjaxService = {
    post: (url, data, headers) => {
        return axios({
            method: "POST",
            url: url,
            headers: headers || { "content-type": "application/json" },
            data: data
        });
    },
};

API承諾:

export const getDashboard = (request) => {
  return AjaxService.post(API_DASHBOARD_URL + "/getDashboard", request
  ).then(
    response => {
      return response.data;
    },
    (error) => {
      return error.response.data;
    }
  )
};

使用 NockJS 進行單元測試:

nock(baseUrl)
    .post(subUrl, request)
    .reply(200, response);

getDashboard(request)
    .then(resp => {
        let compareVal = getNestedObject(resp, keyToCompare);
        let actualVal = getNestedObject(response, keyToCompare);
        expect(compareVal).to.equal(actualVal);
    })
    .then(() => {});

但是當使用 Jest --coverage生成代碼覆蓋率報告時,如下所示:

在此處輸入圖片說明

我們可以看到,在 promise 中,單元測試期間沒有調用成功回調錯誤回調 當應用程序有大量 API 調用時,如何覆蓋這部分代碼,因為它會影響代碼覆蓋率? 還是我沒有測試正確? 請幫助,因為我是單元測試的新手。 提前致謝。

Jest在測試期間運行時才將其計為已覆蓋。

在這種情況下,您getDashboard在測試期間調用了getDashboard ...

...但getDashboard是異步的,測試不會等待它完成。

這意味着測試在getDashboard的異步代碼有機會運行之前同步完成,並且任何尚未運行的代碼都不包含在Jest代碼覆蓋率中。

為了確保代碼正確的測試,並包含在代碼覆蓋率確保您awaitPromise返回由getDashboard

test('getDashboard', async () => {  // <= async test function
  nock(baseUrl)
    .post(subUrl, request)
    .reply(200, response);

  await getDashboard(request)  // <= await the Promise
    .then(resp => {
      let compareVal = getNestedObject(resp, keyToCompare);
      let actualVal = getNestedObject(response, keyToCompare);
      expect(compareVal).to.equal(actualVal);
    })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM