[英]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.