如何在redux-thunk中断言在异步操作内部调度的异步操作

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

本文关键字:异步操作 内部 调度 中断 redux-thunk 断言      更新时间:2023-09-26

我试图断言异步动作是由异步动作分派的,像这样:

// 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中处理两个连续且依赖的异步调用