【问题标题】:Testing an action creator that dispatches multiple action creators测试调度多个动作创建者的动作创建者
【发布时间】:2017-02-23 00:05:11
【问题描述】:

我正在尝试测试这个动作创建器:

export const fetchAllItems = (topicIds)=>{
  return (dispatch)=>{
    topicIds.forEach((topicId, index, array)=>{
      const last = index+1 == array.length;
      dispatch(fetchItems(topicId, last));
    });
  };
};

我想断言fetchItems 已经被调用了两次——第一次是1, false,第二次是2, true。我试过redux-mock-store,但不确定我是否正确使用它:

import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
const store = mockStore();
store.dispatch(fetchAllItems([1, 2])).then(()=>{       
  console.log(store.getActions()); //Throws error: TypeError: Cannot read property 'then' of undefined
});

我也尝试过模拟 dispatch 和 fetchItems,但似乎也无法正常工作。

【问题讨论】:

  • 是否需要在fetchAllItems返回的函数中返回Promise?

标签: javascript reactjs redux react-redux redux-thunk


【解决方案1】:

我通常不使用模拟存储,而是使用spy 来捕获调度的操作

let dispatch = sinon.spy()
fetchAllItems([1, 2, 3])(dispatch)
expect(dispatch).to.have.been.calledWithMatch({ type: "...", ... })

如果 thunk 不直接调度操作,这确实会变得更加困难,但您可以使用 spy 获取 thunk 并重复该过程,直到调度标准操作

let dispatch = sinon.spy()
fetchAllItems([1, 2, 3])(dispatch)
let fetchItems = dispatch.getCall(0).args[0]
fetchItems(dispatch)
expect(dispatch).to.have.been.calledWithMatch({ type: "...", ... })

【讨论】:

  • 注意:我的例子中使用的断言使用了sinon-chai
【解决方案2】:

您的代码的问题是您调用.then,但您的动作创建者没有返回承诺(除非您需要,否则您不必这样做)。您可以将测试更改为:

store.dispatch(fetchAllItems([1, 2]));
console.log(store.getActions());

【讨论】:

  • console.log 的结果是[]。我在想问题是fetchItems 不是一个动作。
  • @AndrewSamuelsen 是的,我认为 fetchItems 是一个动作,因为你正在对它进行调度。
猜你喜欢
  • 2019-01-08
  • 1970-01-01
  • 2018-11-23
  • 1970-01-01
  • 1970-01-01
  • 2018-04-27
  • 2018-06-12
  • 2020-11-21
  • 1970-01-01
相关资源
最近更新 更多