【问题标题】:How to test an action creator with a fetch API request如何使用 fetch API 请求测试动作创建者
【发布时间】:2018-04-13 02:37:23
【问题描述】:

我有一个带有 Redux 和 Jest 的 create-react-app 用于测试。我正在使用 fetch 从动作创建者发出 API 请求。在我编写测试时,我发现无论出于何种原因 - 无论如何我都在尝试模拟这个请求 - 它仍在尝试向 API 发出实际请求并得到一个网络连接错误(所以我从每个请求中都得到了捕获)测试时间)。值得一提的是,这在浏览器中运行良好。

import fetch from 'isomorphic-fetch';
import { SUBMIT_SUCCESS, EMPLOYEE_DETAILS, ERROR } from './actionTypes';
import { API_URL } from '../../Constants';

 export function getEmployeeDetails(id) {
   return async dispatch => {
    try {
      let payload = await (await fetch(`${API_URL}/users/${id}`, {
        method: 'GET',
        headers: { jwt: localStorage.getItem('jwt') },
      })).json();

      dispatch(getEmployeeDetailsSuccess(payload.user));
    } catch (err) {
      dispatch(errorCatch(err));
    }
  };
}

我已经试过了 - https://medium.com/@ferrannp/unit-testing-with-jest-redux-async-actions-fetch-9054ca28cdcd

我也厌倦了这个-https://medium.com/@kellyrmilligan/testing-async-actions-in-redux-with-isomorphic-fetch-and-fetch-mock-35f98c6c2ee7

基本上花了几天的时间来解决这个问题。

我做错了什么?是否有机会获得如何测试此操作的工作示例?

谢谢!

【问题讨论】:

    标签: reactjs testing redux jestjs create-react-app


    【解决方案1】:

    您想具体测试什么?对于模拟fetch,有fetch-mock 之类的东西,但也许您也可以重构您的代码,使其不直接依赖于fetch 工作。

    例如,要检查是否调度了正确的操作,您可以使用以下方式:

    export function getEmployeeDetails(fetcher, id) {
      return async dispatch => {
        let payload = await fetcher(id);
    
        if (/* payload is good */) {
          dispatch(getEmployeeDetailsSuccess(payload.user));
        }
        else {
          dispatch(errorCatch(err))
        }
      };
    }
    

    现在您可以通过传入一个返回好/坏负载的函数和make sure that the right actions are dispatched 来测试您的方法。在普通代码中,您可以像以前一样使用fetch,但传递一个处理该逻辑的函数,而不是将其直接包含在动作创建器中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      • 1970-01-01
      • 2020-11-24
      • 2014-10-27
      • 2016-12-24
      • 2018-04-27
      相关资源
      最近更新 更多