jeffbski / redux-logic-test

redux-logic test utilities to facilitate the testing of logic. Create mock store
MIT License
37 stars 3 forks source link

How to mock api responses with injected httpClient? #8

Open dominikkurbiel opened 6 years ago

dominikkurbiel commented 6 years ago

Hello.

I want to mock responses from api but your example with Promise.resolve(42) returns undefined instead of 42.

Here is my test code:

const injectedDeps = {
  httpClient: {
    get() { return Promise.resolve(42); }
  }
};

describe('appLogic test without reducer', () => {

  describe('appLogic test without reducer', () => {
    let store;

    beforeEach(() => {
      store = createMockStore({
        logic: appLogic,
        injectedDeps,
      });
    });

    it('should fetch answer and dispatch', (done) => {
      store.dispatch({ type: 'EVENT_LIST_FETCH' });
      store.whenComplete(() => {
        expect(store.actions).toEqual([
          { type: 'EVENT_LIST_FETCH' },
          { type: 'EVENT_LIST_SUCCESS', payload: 42 }
        ]);
        done();
      });
    });
  });
});

Here is my httpClient which I injecting to logic middleware:

export default axios.create({
  baseURL: 'http://localhost:5000/api',
});

And I'm using httpClient like this:

export const get = createLogic({
  type: EVENT_LIST.FETCH,
  latest: true,

  processOptions: {
    successType: EVENT_LIST.SUCCESS,
    failType: EVENT_LIST.ERROR,
  },

  process({ httpClient }) {
    return httpClient.get('/event/')
      .then(res => res.data);
  }
});

So the question is how to mock response from httpClient to get the data I want?

jeffbski commented 6 years ago

What you have looks mostly correct, however I see that in one place you were using EVENT_LIST_FETCH and EVENT_LIST_SUCCESS while in the client you are using EVENT_LIST.FETCH and EVENT_LIST.SUCCESS, so if these return the previous values then it should work. So that's the first thing I would check.

Also make sure your appLogic array includes the get logic you created.

dominikkurbiel commented 6 years ago

@jeffbski I'm using EVENT_LIST.FETCH from types.js. Everythink works fine on the front end side, but I can't test it. Hovewer if I incject :

  httpClient: axios.create({
     baseURL: 'http://localhost:5000/api',
   }),

instead of :

  httpClient: {
    get() { return Promise.resolve(42); }
  }

and my API is working I get real data from my database. I'm even trying to mock data with moxios, axios-mock-adapter, and even jest.genMockFromModule('axios') and I can not make it work :(

jeffbski commented 6 years ago

In looking at your code, it looks like it would be expecting the data property to have the value. So your mock would need to match that expectation.

So change your mock to

const injectedDeps = {
  httpClient: {
    get() { return Promise.resolve({ data: 42}); }
  }
};