reduxredux-thunkredux-mock-storefetch-mock

Action call is returning 'undefined' with fetch-mock


Action "type": undefined, is what I keep getting returned when I try to test a redux action with fetch-mock. Any suggestion on how to resolve this issue? Could it be a bug in fetch-mock?

Expected value to equal:
[{"type": undefined}, {"result": {"hello": "world"}, "type": undefined}]
Received:
[{"type": "DASHBOARD_RESULT_LOADING"}, {"result": {"hello": "world"}, "type": "DASHBOARD_RESULT_READY"}]

dashboardActions.js

function resultReady(json) {
return {
type: DASHBOARD_RESULT_READY,
result: camelizeKeys(json)
 };
}

export function requestPredict(params) {
let url = `${process.env.API_URL}/predict/`;
const requestParams = {
  method: 'post',
  credentials: 'include'
};

return async (dispatch) => {
return fetch(url, requestParams)
  .then(response => {
    if (response.status === 200) {
      return response.json();
    } else {
      throw Error(response.statusText);
    }
  })
  .then(data => dispatch(resultReady(data)));
};
}

dashboardActions.test.js

const mockData = { 
"hello": "world"
}


describe('action creators', () => {

afterEach(() => {
fetchMock.reset()
})

it('should create DASHBOARD_RESULT_LOADING', () => {
 fetchMock.post('*', {"hello":"world"} );

const expectedActions = [
 { type: actions.DASHBOARD_RESULT_LOADING },
 { type: actions.DASHBOARD_RESULT_READY, result: mockData }
]

const store = mockStore({ result: {}})

return store.dispatch(actions.requestPredict())
 .then((data) => {
  expect(store.getActions()).toEqual(expectedActions)
 })
})
})

Solution

  • You're receiving types "DASHBOARD_RESULT_LOADING" and "DASHBOARD_RESULT_READY", which seems to be the intended behaviour. You're expecting actions.DASHBOARD_RESULT_LOADING and actions.DASHBOARD_RESULT_READY, neither of which seems to be defined with any value.

    Either define actions.DASHBOARD_RESULT_LOADING and actions.DASHBOARD_RESULT_READY:

    actions.DASHBOARD_RESULT_LOADING = 'DASHBOARD_RESULT_LOADING'
    actions.DASHBOARD_RESULT_READY = 'DASHBOARD_RESULT_READY'
    

    or replace them with your expected types:

    const expectedActions = [
      {
        type: 'DASHBOARD_RESULT_LOADING'
      },
      {
        type: 'DASHBOARD_RESULT_READY',
        result: mockData
      }
    ]