singard
singard

Reputation: 107

How to test react component with mock api calls

I am trying to run tests for one React Component; however, the state of this component is set based on the response getting from an API call.

componentDidMount() {
  getStatus().then(status => {
    this.setState({status: status});
  });
}

Is there a way to mock this response using Mocha instead of actually hitting the API? Since this is in componentDidMount(), I will always get to this block using Enzyme's shallow and mount, and it throws fetch is not defined error

I can get rid of this error by importing isomorphic-fetch in my test setup file, but I would prefer to just mock a fake api and make up the response.

Upvotes: 2

Views: 2654

Answers (1)

fyasir
fyasir

Reputation: 2970

Use fetch-mock to mock isomorphic-fetch api calls.

var fetchMock = require('fetch-mock');

describe('Test mocking isomorphic-fetch', function() {
  before(function() {
    fetchMock.get('/my/api/endpoint', {hello: 'world'});
  });

  after(function() {
    fetchMock.restore();
  });

  it('should mock fetch', function() {
    // your test code here
  });
});

Upvotes: 1

Related Questions