I am new to react and trying to writing my first test case using Jest. I have to mock a fetch response. I am using jest-fetch-mock. But the call is going to actual fetch and data returned is undefined.
package.json :
"jest-fetch-mock": "^2.1.2"
setupTest.js file
global.fetch = require('jest-fetch-mock');
Actual api call method:
static fetchUserInfo(){
return dispatch => {
fetch('https://localhost:55001/api/userInfo')
.then(this.httpResponseHandler.handleHttpResponse)
.then ((resp) => resp.json())
.then(data => dispatch(this.onUserInfoGetSuccess(data)))
.catch( error => {
dispatch(this.onFetchFailure(error));
});
};
}
Test case
it('should get user info', () => {
fetch.mockResponse(JSON.stringify({
"name": "swati joshi",
}
));
let data = ActualDataApi.fetchUserInfo();
console.log(data);
expect(data.name).toEqual('swati joshi');
}
As fetchUserInfo
is dispatcher (using Redux with React) then how to mock it?
Thanks in Advance!