lundi 7 janvier 2019

Getting [TypeError: Cannot read property 'map' of undefined] when testing fetch call redux action

I'm using redux action to make a fetch call in witch I have a map function to the result coming from the Promise. When I try to test the action with fetch-mock I get an error: [TypeError: Cannot read property 'map' of undefined].

This is the part from action.js file:

export const requestChartData = () => (dispatch) => {
dispatch({type: REQUEST_CHART_DATA_PENDING})

return 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}))        
}

This is the part from action.test.js:

import * as actions from '../../actions/index'
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 thunk from 'redux-thunk'
import configureMockStore from 'redux-mock-store'

import fetchMock from 'fetch-mock'

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

describe('async actions', () => {
afterEach(() => {
  fetchMock.restore()
})

it('creates REQUEST_CHART_DATA_SUCCESS when fetching data has been done', () => {
  fetchMock.getOnce('https://swapi.co/api/people', {
    data: { results: ['testing', 'test']},
    data: { results: ['testing', 'test']},
    headers: { 'content-type': 'application/json' }
})


  const expectedActions = { 
      type: REQUEST_CHART_DATA_SUCCESS, labels: {data: { results: ['testing', 'test']}},
        chartData: {data: { results: ['testing', 'test']}}
  }

  const store = mockStore({labels: {data: { results: []}},
    chartData: {data: { results: []}}})

  const action = store.getActions()

  return store.dispatch(actions.requestChartData()).then(() => {
    // return of async actions
    expect(action[1]).toEqual(expectedActions)
    })
    })
})

Aucun commentaire:

Enregistrer un commentaire