【问题标题】:Testing React Redux Async Actions with fetch-mock - "Cannot read property 'then' of undefined"使用 fetch-mock 测试 React Redux 异步操作 - “无法读取未定义的属性 'then'”
【发布时间】:2018-12-11 16:53:50
【问题描述】:

我在测试 react redux 异步操作时遇到了一些问题,由于某种原因,store.dispatch 返回 undefined 并且 .then 方法不起作用。

当我 console.log store.dispatch(actions.requestChartData()) 时,它给了我以下错误:

fetch-mock:没有为 GET 定义回退响应 https://swapi.co/api/people

witch 表示没有模拟响应且未定义。

我不知道我的错误在哪里,在 url 或我缺少的东西中。任何帮助将不胜感激

这是我的 action.js 代码:

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

还有我的 action.test.js 文件:

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

【问题讨论】:

    标签: javascript reactjs testing react-redux fetch-mock


    【解决方案1】:

    在您的 requestChartData 操作创建者中,返回 fetch 而不是仅仅调用它。 return fetch('/your-api-path')

    【讨论】:

      猜你喜欢
      • 2017-12-09
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      • 2018-11-18
      • 2018-02-11
      • 2020-10-10
      • 2019-02-15
      • 2022-01-03
      相关资源
      最近更新 更多