繁体   English   中英

如何断言在redux-thunk中的异步动作中分派的异步动作

[英]how to assert an async action dispatched inside an async action in redux-thunk

我试图断言异步动作是由如下所示的异步动作调度的:

// synchronous actions
export const getObjects = () => ({ type: 'GET_OBJECTS' });
export const addObject = object => ({ type: 'ADD_OBJECT', object });

// an async action
export const getObjectsAsync = () => 
  dispatch =>
    axios.get(URL).then((data) => {
      dispatch(getObjects());
    });

// another async action that dispatches the previous async action
export const postObjectAsync = newObject =>
  dispatch =>
    axios.post(URL, newObject)
      .then(() => { dispatch(addObject(newObject)); })
      .then(() => { dispatch(getObjectAsync()); });

// the test
describe('postObjectAsync()', () => {
  it('should return ADD_OBJECT and GET_OBJECT actions', () => {
    const object = mockedObject;
    const store = mockedStore;
    const expectedActions = [
     { type: 'ADD_OBJECT', object },
     { type: 'GET_OBJECTS', objects }, // I expected to see this object on store.getActions()[1]
    ];
    return store.dispatch(postObjectAsync(object))
      .then(() => {
        store.getActions().should.deep.equal(expectedActions);
        // AssertionError: expected [ Array(1) ] to deeply equal [ Array(2) ]
      });
  });
});

我希望store.getActions()包含一个同时包含GET_OBJECTS和ADD_OBJECT操作的数组,但它仅包含ADD_OBJECT操作

有人可以称体重吗?

想通了,问题不在测试中,

// another async action that dispatches the previous async action
export const postObjectAsync = newObject =>
  dispatch =>
    axios.post(URL, newObject)
      .then(() => { dispatch(addObject(newObject)); })
      .then(() => { dispatch(getObjectAsync()); });

应该

// another async action that dispatches the previous async action
export const postObjectAsync = newObject =>
  dispatch =>
    axios.post(URL, newObject)
      .then(() => { 
        dispatch(addObject(newObject));
        return dispatch(getObjectAsync());
      });

我只是意识到不应该在同步函数上使用.then()。 这篇文章有帮助: 如何在Redux中处理两个连续且相关的异步调用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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