如何在redux中测试调度异步操作创建者的结果



我在react redux中有这个动作创建者,它在单击按钮后被调度。此AC删除用户帖子。单击一个按钮会运行操作,该操作首先进行一些firebase调用,如果成功,它会将操作创建者本身发送到redux,然后在redux存储中进行一些更改。当这些更改完成后,我的组件会自动更新,并且删除的帖子会消失。我想用jest/酶来测试这个功能。我模拟按下删除按钮,但我不知道如何等待firebase调用结束,然后才能测试firebase调用成功后的结果。我必须强调,在常规应用程序中,一切都正常工作。我的问题是,我的测试根本没有等待这些调用结束,而是完成了。我如何才能等待这些火球呼叫结束,然后才能测试成功后的结果?

// post component
// In post component onClick on a button just calls action like this: 
onRemovePost({ index: post.index, authorModifiedEmail: author.modifiedEmail, hasUrl: !!post.url });

// action creator 
export const removePost = (post) => {
const { index, authorModifiedEmail, hasUrl } = post;
return async (dispatch) => {
const updates = {};
updates[`users/${authorModifiedEmail}/posts/posts/${index}`] = null;
try {
await fire.database().ref().update(updates);
hasUrl && (await fire.storage().ref(`users/${authorModifiedEmail}/posts/${index}`).delete());
dispatch({ type: actionTypes.REMOVE_POST, user: authorModifiedEmail, index });
} catch (error) {
failToast(error.message);
}
};
};
// test
test('removes post after clicking remove button', async () => {
// initializing wrapper here with relevant props
const postEditionIcon = findByTestAttr(wrapper, 'post-edition-icon').first();
postEditionIcon.simulate('click');
const removeBtn = findByTestAttr(wrapper, 'remove-btn');
await removeBtn.simulate('click');
const post = findByTestAttr(wrapper, 'post-component');
expect(post.exists()).toBe(false);
})

您可以这样尝试:

test('action creator is returned',()=>{ 
return actionCreator().then((response) => {
//write your assertion here
const post = findByTestAttr(wrapper, 'post-component');
expect(post.exists()).toBe(false);
});
});

最新更新