使用react-testing-library测试useContext时cart.length读取报错如何解决
问题根因
你传入的测试状态结构和实际Context要求的状态结构不匹配:
- 你定义的
initialCartState是对象结构{ cart: 购物车数组 } - 测试代码中传入的
testState直接是购物车数组,组件中读取state.cart时得到undefined,调用.length就抛出了类型错误。
修复步骤
1. 修正测试中的状态结构
将测试里的testCartState调整为和正式状态一致的对象结构:
const testCartState = { cart: [ { productId: 2, title: "Apple iPhone 11 Green", addedDate: "Thu Oct 07 2021 19:49:48 GMT+0300 (GMT+03:00)", }, { productId: 2, title: "Apple iPhone 11 Green", addedDate: "Thu Oct 07 2021 19:49:48 GMT+0300 (GMT+03:00)", }, { productId: 2, title: "Apple iPhone 11 Green", addedDate: "Thu Oct 07 2021 19:49:48 GMT+0300 (GMT+03:00)", }, { productId: 2, title: "Apple iPhone 11 Green", addedDate: "Thu Oct 07 2021 19:49:48 GMT+0300 (GMT+03:00)", }, ] };
2. 修正Context组件的参数拼写错误
Context组件接收的参数testproductDispatch拼写和测试传参不一致,测试里传的是驼峰写法testProductDispatch,修改Context参数对齐即可:
export const Context = ({ children, testState, testProductState, testProductDispatch, // 此处修正拼写,和测试传参保持一致 testDispatch, }) => { // 原有逻辑不变 const [iState, iDispatch] = useReducer(cartReducer, initialCartState); const [iProductState, iProductDispatch] = useReducer(productReducer, initialProductState); const state = testState ? testState : iState; const dispatch = testDispatch ? testDispatch : iDispatch; const productState = testProductState ? testProductState : iProductState; const productDispatch = testProductDispatch ? testProductDispatch : iProductDispatch; // 原有逻辑不变 }
3. 可选:补充删除逻辑测试
如果要验证删除功能是否正常,可以在现有测试基础上补充触发点击、验证dispatch调用的逻辑:
fireEvent.click(screen.getByTestId("remove-button")); // 替换为你实际定义的删除action结构即可 expect(dispatch).toHaveBeenCalledWith({ type: 'REMOVE_FROM_CART', payload: 2 });
内容的提问来源于stack exchange,提问作者Deniz Firat
相关产品推荐
相关产品推荐

