I want to test the API call in my React component and also tried few ways by surfing the net.
MyComponent:
export const API = {
getData() {
return fetch(localStorage.blobUrl).then(res => res.blob())
}
}
const downloadArchiveFile = () => {
localStorage.setItem('blobUrl',bloburl);
API.getData().then((blob) => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.style.display = "none";
a.href = url;
// the filename you want
a.download = templateName;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
})
};
MyComponent.test.js
it('api call', async () => {
const fakeUserResponse = {
'myResponse': {
'a': '1',
'b': '2' }
};
var apiFunc = jest.spyOn(API, 'getData').mockImplementationOnce(() => {
return Promise.resolve({
json: () => Promise.resolve(fakeUserResponse)
})
})
})
Test case is getting passed. But while seeing code coverage this code is not covered.
See the code coverage report
Links which I refer:
React - how do I unit test an API call in Jest?
Code coverage concern on promise/asynchronous unit testing using nockjs and jest