Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/445.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 测试分派多个动作创建者的动作创建者_Javascript_Reactjs_Redux_React Redux_Redux Thunk - Fatal编程技术网

Javascript 测试分派多个动作创建者的动作创建者

Javascript 测试分派多个动作创建者的动作创建者,javascript,reactjs,redux,react-redux,redux-thunk,Javascript,Reactjs,Redux,React Redux,Redux Thunk,我有一个正在尝试测试的操作创建者: export const fetchAllItems = (topicIds)=>{ return (dispatch)=>{ topicIds.forEach((topicId, index, array)=>{ const last = index+1 == array.length; dispatch(fetchItems(topicId, last)); }); }; }; 我想断言,

我有一个正在尝试测试的操作创建者:

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

我也尝试过模仿
调度
获取项目
,但似乎也无法实现。

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

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

我通常不使用模拟存储,而是使用

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: "...", ... })

是否需要通过
fetchAllItems
在返回的函数中返回
Promise
?该
控制台.log
的结果是
[]
。我认为问题在于
fetchItems
不是一个动作。@AndrewSamuelsen是的,我假设
fetchItems
是一个动作,因为您正在对它进行分派。注意:我的示例中使用的断言利用了