dimanche 4 novembre 2018

How to mock qraphQL/Apolloe query response for testing action-creator in redux?

As I didn't have much experience with graphQL/Apollo, mocking query response for testing with Jest got me confused. I have the following action creator:

export const fetchSomething = _id => (dispatch) => {
  client.query({
    query: gql`
    {
      something(_id: "${_id}") {
        _id
        somedata
      }
    }`,
  })
    .then(something => dispatch({
      type: FETCH_SOMETHING,
      payload: something.data,
    }));
};

And the following test which doesn't work

  describe('fetchSomething', () => {
    it('should dispatch correct type and data correctly', async () => {
      const dispatch = jest.fn();
      client.query =
        async () => new Promise(resolve => resolve({ something: 'something' }));
      await fetchSomething('xxx')(dispatch);
      expect(dispatch).toHaveBeenCalledWith({ type: FETCH_SOMETHING,   payload: {something: 'something');
    });
  });

ApolloClient.js file of mine

import ApolloClient from 'apollo-boost/lib/index.umd';

const client = new ApolloClient({
  uri: 'http://localhost:5000/graphql',
});

export default client;

Usually, for methods like fetch, it is enough to resolve promise to mock the response. Which doesn't work for graphql/apollo for me now. How can I mock the response in this case?

thanks in advance

Aucun commentaire:

Enregistrer un commentaire