简体   繁体   中英

Testing an action creator that dispatches multiple action creators

I have this action creator I am attempting to test:

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

I'd like to assert that fetchItems has been called twice - first with 1, false and second with 2, true . I've tried redux-mock-store , but not sure I'm using it right:

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

I've also tried mocking dispatch and fetchItems but can't seem to get that working either.

Instead of using a mock store, I usually just use a spy to capture the dispatched actions

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

This does get harder if the thunk does not dispatch the action directly, but you can use the spy to get the thunk and repeat the process until standard actions are dispatched

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

The problem with your code is that your calling .then , but your action creator does not return a Promise (which you don't have to unless you need it). You can change your tests to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM