Alec Ventura
Alec Ventura

Reputation: 21

Testing async calls with Jest, redux-mock-store and Moxios

I create a simple case to test my actions, but my store.dispatch is not returning a promise. Can someone tell me what is wrong?

Action.js code:

export const handleSubmit = inputData =>
(dispatch) => {
axios.post(`${API_URL}/process-input/`, { input: inputData })
  .then((resp) => {
    dispatch({
      type: 'UPDATE_OUTPUT',
      payload: resp.data,
    });
  })
  .catch((e) => {
    dispatch({
      type: 'UPDATE_OUTPUT',
      payload: e.message,
    });
  });

};

And my test:

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import moxios from 'moxios';
import * as actions from './../../../../src/modules/inputData/action';
import { API_URL } from './../../../../src/constants';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

describe('InputData actions', () => {
 test('Test input value update', () => {
 moxios.install();
 moxios.stubRequest(`${API_URL}/process-input/`, { status: 200, response: 'A nice test result' });
 const store = mockStore();

 return store.dispatch(actions.handleSubmit('anyData'))
  .then(() => {
    expect(store.getActions()).toEqual([
      { type: 'UPDATE_OUTPUTT', payload: 'A nice test result' },
    ]);
  });

}); });

The error that is returning is: Cannot read property 'then' of undefined

Upvotes: 2

Views: 638

Answers (1)

Naman Parashar
Naman Parashar

Reputation: 263

Your redux action is not returning a promise. You should return the axios.post function.

export const handleSubmit = inputData =>
(dispatch) => {
return axios.post(`${API_URL}/process-input/`, { input: inputData })
  .then((resp) => {
    dispatch({
      type: 'UPDATE_OUTPUT',
      payload: resp.data,
    });
  })
  .catch((e) => {
    dispatch({
      type: 'UPDATE_OUTPUT',
      payload: e.message,
    });
  });
};

Upvotes: 2

Related Questions