Nick Brady
Nick Brady

Reputation: 6582

How to test api calls using fetch

I can't find a definitive answer on what the proper way to unit test fetch is online. I'm using the create-react-app build. so far this is the closest I've found where a user recommends using nock & node-fetch. I have seen some development on a library here: https://github.com/wheresrhys/fetch-mock but it's build is failing which makes me nervous.

Goal is to make this play nicely with jest

Does anyone have any recommendations from experience on the best way to test request using the fetch api?

Upvotes: 1

Views: 3671

Answers (1)

Martin Dawson
Martin Dawson

Reputation: 7656

You should use fetch-mock like you linked to test the new fetch api calls.

The fact that the build is failing means absolutely nothing to you. This is just for the devs to know when committing to github for continuous development. When you use npm i --save-dev fetch-mock it will download a (hopefully) working release version that the github author specifically publishes, not the failing build.

Example from my project for a redux thunk action:

import expect from 'expect';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';

import * as actions from './formActions';

const mockStore = configureStore([thunk]);
const store = mockStore({});
const body = {
  email: '[email protected]',
};

describe('registerFormActions', () => {
  let calledActions;

  beforeEach(() => {
    store.clearActions();
    calledActions = store.getActions();
  });

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

  it('should post form', () => {
    fetchMock.postOnce('/account/register', body);

    store.dispatch(actions.submit()).then(() => {
      expect(fetchMock.called('/account/register')).toBe(true);
    });
  });
});

export const submit = formData => dispatch =>
fetch('/account/register', {
  method: 'post',
  body: formData,
  credentials: 'same-origin',
}).then((response) => {
  if (response.ok) {
     // Do something cool
  }
});

Upvotes: 4

Related Questions