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

React测试入门报错:useDispatch找不到Redux上下文值

解决React测试中AddTodo组件的Redux Context错误

问题根源

AddTodo组件使用了useDispatch钩子,该钩子必须在Redux的<Provider>组件包裹的上下文中才能正常工作。你的测试代码直接渲染<AddTodo />,没有提供这个上下文,所以触发了找不到Redux context的错误。

两种修复方案

方案1:用测试Store包裹组件

创建一个测试专用的Redux Store,并用<Provider>包裹待测试组件,还原组件的运行环境:

import { render, screen } from '@testing-library/react';
import { Provider } from 'react-redux';
import { configureStore } from '@reduxjs/toolkit';
import AddTodo from './AddTodo';
import todoReducer from '../redux/todoSlice';

// 初始化测试用Store
const testStore = configureStore({
  reducer: {
    todos: todoReducer, // 对应你项目中Store的reducer命名
  },
});

test('标题应渲染"Add Todo"', () => {
  render(
    <Provider store={testStore}>
      <AddTodo />
    </Provider>
  );
  const headingElement = screen.getByText('Add Todo');
  expect(headingElement).toBeInTheDocument();
});

方案2:模拟useDispatch钩子(仅UI测试场景)

如果你的测试只需要验证UI渲染(比如标题是否存在),不需要测试dispatch逻辑,可以用Jest直接模拟useDispatch,避免依赖Redux上下文:

import { render, screen } from '@testing-library/react';
import AddTodo from './AddTodo';
import { useDispatch } from 'react-redux';

// 模拟useDispatch,返回空函数即可
jest.mock('react-redux', () => ({
  ...jest.requireActual('react-redux'),
  useDispatch: jest.fn(() => () => {}),
}));

test('标题应渲染"Add Todo"', () => {
  render(<AddTodo />);
  const headingElement = screen.getByText('Add Todo');
  expect(headingElement).toBeInTheDocument();
});

额外提示:组件中使用的自定义<heading>标签不符合HTML规范,建议替换为<h2>等标准标题标签,提升语义化程度。

内容的提问来源于stack exchange,提问作者seanrandevs

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:10:29