Swati Joshi
Swati Joshi

Reputation: 105

Using Jest even after doing fetch.mockResponse actual fetch is getting called

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!

Upvotes: 3

Views: 8247

Answers (1)

Brian Adams
Brian Adams

Reputation: 45780

It's possible that fetch isn't mocked correctly...but it looks like your primary issue is that fetchUserInfo returns a function.

The function that it returns should be called on a dispatch mock to verify that it dispatches the correct action.

Also note that the function returned by fetchUserInfo is asynchronous so you'll need a way to wait for it to finish during your test.

If you modify the function returned by fetchUserInfo to return the Promise like this:

static fetchUserInfo(){
  return dispatch => {
    return fetch('https://localhost:55001/api/userInfo')  // <= return the Promise
      .then(this.httpResponseHandler.handleHttpResponse)
      .then((resp) => resp.json())
      .then(data => dispatch(this.onUserInfoGetSuccess(data)))
      .catch(error => {
        dispatch(this.onFetchFailure(error));
      });
  };
}

...then you can test it like this:

it('should get user info', async () => {  // <= async test function
  fetch.mockResponse(JSON.stringify({
    "name": "swati joshi",
  }));

  let func = ActualDataApi.fetchUserInfo();  // <= get the function returned by fetchUserInfo
  const dispatch = jest.fn();
  await func(dispatch);  // <= await the Promise returned by the function
  expect(dispatch).toHaveBeenCalledWith(/* ...the expected action... */);
});

Upvotes: 0

Related Questions