Redux Thunk中Mock Axios响应失败问题排查求助
Redux Thunk中Mock Axios响应失败问题排查与修复
问题现象
测试Redux Thunk的requestProduct异步action时,Mock的Axios响应始终未生效,Thunk中axios.put返回undefined,导致后续判断response.status === 200的逻辑、dispatch通知动作以及组件回调都无法执行。
错误原因
- 测试执行顺序错误:先触发按钮点击(触发action执行),再设置Axios的Mock响应。当action开始执行时,Axios尚未被Mock,因此
axios.put返回默认的undefined。 - 组件参数缺失:
handleRequest里定义的callback没有传入requestProduct的参数中,即使Mock成功,组件的状态更新逻辑也不会触发。
修复步骤
1. 调整Mock与交互顺序
先设置Axios的Mock响应,再触发按钮点击,确保action执行时Mock已生效。
2. 处理异步逻辑
Thunk是异步函数,测试需要等待异步操作完成,使用async/await配合React Testing Library的waitFor处理异步流程。
3. 补全组件参数传递
在组件的productInfo中加入callback,确保Thunk能调用到组件的回调函数。
完整修复代码
组件代码修改(补全callback传递)
const handleRequest = () => { setProductSaving(true) const callback = (response) => { if (response.status === 200) { setProductSaving(false) setProductRequested(true) } } const productInfo = { // 原有product input参数 callback // 新增:传递callback到Thunk } dispatch(requestProduct(productInfo)) }
测试代码修改
import { waitFor } from '@testing-library/react'; jest.mock('axios'); test('should be able to request product', async () => { // 1. 先定义Mock响应 const mockedResponse = { data: { message: "SMEProductTagAddedSuccessfully"}, status: 200, statusText: 'OK', }; axios.put.mockResolvedValueOnce(mockedResponse); // 2. 渲染组件 const { getByTestId } = render( <Router> <Provider store={store}> <ThemeProvider theme={techpathTheme}> <ProductCard product={product} /> </ThemeProvider> </Provider> </Router> ) // 3. 触发交互 fireEvent.click(getByTestId('requestbtn')) // 4. 等待异步逻辑完成并验证结果 await waitFor(() => { // 验证是否dispatch了成功通知 const actions = store.getActions(); expect(actions).toContainEqual({ type: NOTIFY_STATUS, payload: { message: "SMEProductTagAddedSuccessfully", variant: 'success', }, }); // 可额外验证组件状态更新(需对应测试节点) // expect(getByTestId('saving-indicator')).not.toBeInTheDocument(); }); // 验证Axios调用是否符合预期 expect(axios.put).toHaveBeenCalledWith( `/product/${product.smeId}/user/${product.userId}`, // 替换为实际预期URL expect.any(Object) // 替换为实际预期请求体 ); })
内容的提问来源于stack exchange,提问作者SFernando
相关产品推荐
相关产品推荐

