![](/img/trans.png)
[英]How to code coverage a promise inside functions while unit testing using 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
代碼覆蓋率中。
為了確保代碼正確的測試,並包含在代碼覆蓋率確保您await
的Promise
返回由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.