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
是一个动作,因为您正在对它进行分派。注意:我的示例中使用的断言利用了