I have written a simple unit test for API call using NockJS and Jest for a react application as bellow:
AjaxService.js
export const AjaxService = {
post: (url, data, headers) => {
return axios({
method: "POST",
url: url,
headers: headers || { "content-type": "application/json" },
data: data
});
},
};
API Promise:
export const getDashboard = (request) => {
return AjaxService.post(API_DASHBOARD_URL + "/getDashboard", request
).then(
response => {
return response.data;
},
(error) => {
return error.response.data;
}
)
};
Unit test using 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(() => {});
But when the code-coverage report is generated using Jest --coverage
as below:
We can see that in promise, success callback and error callback is not called during unit test. How to cover this part of code as it affects code-coverage percentage when an application is having numerous API calls? Or am I not testing is properly? Please help as I am new to unit testing. Thanks in advance.