You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 13:24:04