mardi 31 octobre 2017

How to test an action creator with a fetch API request

I have a create-react-app with Redux and Jest for testing. I am using fetch to make the API request from an action creator. As I am writing tests I found that for what ever reason – anyway I am trying to mock this request - it is still trying to make the actual request to the API and getting a Network Connection Error (so I get the catch from the request each time when test). It might be worth mentioning that this works fine in the browser.

import fetch from 'isomorphic-fetch';
import { SUBMIT_SUCCESS, EMPLOYEE_DETAILS, ERROR } from './actionTypes';
import { API_URL } from '../../Constants';

 export function getEmployeeDetails(id) {
   return async dispatch => {
    try {
      let payload = await (await fetch(`${API_URL}/users/${id}`, {
        method: 'GET',
        headers: { jwt: localStorage.getItem('jwt') },
      })).json();

      dispatch(getEmployeeDetailsSuccess(payload.user));
    } catch (err) {
      dispatch(errorCatch(err));
    }
  };
}

I have tried this - http://ift.tt/2l2sRpt

I have also tired this - http://ift.tt/2zUVedH

And basically spent a couple of days trying to work on this.

What am I doing wrong? Any chance to get a working example of how to test this action?

Thank you!

Aucun commentaire:

Enregistrer un commentaire