I have some problems with testing react redux async actions, for some reason store.dispatch returns undefined and .then method doesn't work.
When I console.log the store.dispatch(actions.requestChartData()) it gives me the following error:
fetch-mock: No fallback response defined for GET to https://swapi.co/api/people
witch means that there is no mock response and it's undefined.
I don't know where is my mistake, in the url or something that i'm missing. Any help will be appreciated
Here're my action.js code:
import {
ROOT_URL,
API_KEY,
FETCH_POSTS,
CREATE_POST,
REQUEST_CHART_DATA_PENDING,
REQUEST_CHART_DATA_SUCCESS,
REQUEST_CHART_DATA_FAILED
} from '../constants/constants'
export const requestChartData = () => (dispatch) => {
dispatch({type: REQUEST_CHART_DATA_PENDING})
fetch('https://swapi.co/api/people')
.then(response => response.json())
.then(data => dispatch({type: REQUEST_CHART_DATA_SUCCESS,
labels: data.results.map(label => label.name),
chartData: data.results.map(chartData => chartData.height )}))
.catch(error => dispatch({type: REQUEST_CHART_DATA_FAILED, payload: error}))
}
And my action.test.js file:
import * as actions from '../../actions/index'
import fetchMock from 'fetch-mock'
import {
ROOT_URL,
API_KEY,
FETCH_POSTS,
CREATE_POST,
REQUEST_CHART_DATA_PENDING,
REQUEST_CHART_DATA_SUCCESS,
REQUEST_CHART_DATA_FAILED
} from '../../constants/constants'
import thunkMiddleware from 'redux-thunk'
import configureMockStore from 'redux-mock-store'
const mockStore = configureMockStore([thunkMiddleware])
describe('fetching api url', () => {
afterEach(() => {
fetchMock.restore()
})
it('creates REQUEST_CHART_DATA_SUCCESS when fetching has been done', () => {
fetchMock.getOnce('https://swapi.co/api/people', {
body: { todos: ['do something'] },
headers: { 'content-type': 'application/json' }
})
const expectedActions =
{ type: REQUEST_CHART_DATA_SUCCESS, body: { todos: ['do something'] } }
const store = mockStore({ todos: [] })
return store.dispatch(actions.requestChartData()).then(() => {
expect(store.getActions()).toEqual(expectedActions)
})
})
})
In your requestChartData action creator, return the fetch instead of just calling it. return fetch('/your-api-path')