我正在尝试断言异步操作是由异步操作调度的,如下所示:
// 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操作
任何人都可以称重吗?
答案 0 :(得分:0)
想出来,问题不在测试中,
// 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()。 这篇文章帮助:How to handle two consecutive and dependant async calls in redux