【问题标题】:.forEach within async action creator not returning action when running unit test运行单元测试时异步动作创建者中的.forEach不返回动作
【发布时间】:2017-12-09 18:57:01
【问题描述】:

我正在使用 react/redux 生成一个面板列表,每个面板显示每个列表项上的数据。我设置了一个 5 秒的间隔来调用 refreshAppList(this.props.list) 操作创建者,该操作创建者 forEach 循环遍历列表中的每个项目并进行异步调用,然后调度刷新的列表项(使用 redux-thunk)。所以基本上,我每 5 秒刷新一次包含最新数据的面板列表。这很好用!不幸的是,现在我正在为这个特定的异步操作创建器编写单元测试,我遇到了一个问题。 .forEach 不返回任何东西,所以当我在单元测试中调用它时,我变得不确定。有谁知道如何解决这个问题,或者我可能需要使用不同的方法来刷新整个面板列表?

这是遍历数组并对每个数组项进行异步调用的动作创建者。

export const refreshAppList = list => (dispatch) => {
  list.forEach((version, index) => {
    const url = `apiEndpoint/${version.data.app_id}/${version.data.version}`;
    return axios.get(url)
      .then(({ data }) => {
        data.uniqueId = version.uniqueId;
        data.refreshId = uuidv1();
        dispatch({ type: REFRESH_APP_LIST, payload: { index, data } });
      })
      .catch((e) => {
      console.log(e);
      });
   });
 };

这是我收到的错误:

 1) async actions creates an action with type: REFRESH_APP_LIST:
 TypeError: Cannot read property 'then' of undefined
  at Context.<anonymous> (tests/asyncActions.js:140:12)

这是我在测试中调用动作创建者的地方(使用 redux-mock-store):

return store.dispatch(refreshAppList(list)).then(() => {
  expect(store.getActions()).to.deep.equal(expectedActions);
});

我认为还值得一提的是,我正在使用 axios-mock-adapter 来模拟从 action creator 中的异步调用返回的数据。

最后一件事:我已经为同一个应用程序中的另外两个异步操作创建者编写了单元测试,并且都通过了。最大的区别在于,这个特定的动作创建者使用 forEach 循环将多个异步调用链接在一起(即不返回任何内容给测试)。

【问题讨论】:

    标签: unit-testing reactjs redux mocha.js chai


    【解决方案1】:

    这不起作用,因为refreshAppList 返回的函数不返回任何内容。此外,.forEach 不会返回任何内容,即使您确实从内部返回了 axios.get.。您可以改用.map 并返回Promise.all 中的所有内容。像这样的

    export const refreshAppList = list => (dispatch) => {
      return Promise.all(list.map((version, index) => {
        const url = `apiEndpoint/${version.data.app_id}/${version.data.version}`;
        return axios.get(url)
          .then(({ data }) => {
            data.uniqueId = version.uniqueId;
            data.refreshId = uuidv1();
            dispatch({ type: REFRESH_APP_LIST, payload: { index, data } });
          })
          .catch((e) => {
          console.log(e);
          });
       }));
     };
    

    【讨论】:

    • 太棒了!我刚刚意识到我应该说refreshAppList 返回的函数 没有返回任何东西(哎呀)。真高兴你做到了。 :)
    猜你喜欢
    • 1970-01-01
    • 2018-04-27
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多