测试提取调用Redux操作

时间:2019-01-07 14:39:09

标签: reactjs testing redux fetch-mock

我正在使用redux动作进行提取调用,在该调用中,我具有对Promise的结果进行映射的功能。当我尝试使用fetch-mock测试操作时,出现错误:[TypeError:无法读取未定义的属性'map'。

这是来自action.js文件的部分:

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

这是来自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)
    })
    })
})

0 个答案:

没有答案