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

如何使用Redux Toolkit与Vitest监视useAppDispatch()返回的dispatch实例

测试中监视useAppDispatch返回的dispatch实例的方法

你当前的代码仅监视了useAppDispatch钩子本身的调用,而非它返回的dispatch函数。要断言特定action(比如resetStates())是否被dispatch,需要先mockuseAppDispatch,让它返回一个可追踪的mock函数,具体步骤如下:

步骤1:提前mock useAppDispatch

在测试文件顶部,通过vitest的vi.mock替换redux store模块中的useAppDispatch,让它返回一个预定义的mock dispatch函数:

import { vi, waitFor } from 'vitest';
import { render } from '@testing-library/react';
import * as redux from "@/core/context/redux/store";
import { resetStates } from '@/path/to/your/actions'; // 导入你要断言的action
import MockForgeViewer from './MockForgeViewer';

// 创建mock dispatch函数
const mockDispatch = vi.fn();

// 替换原模块的useAppDispatch
vi.mock('@/core/context/redux/store', () => ({
  // 保留模块其他原有导出
  ...vi.importActual('@/core/context/redux/store'),
  // 让useAppDispatch返回mockDispatch
  useAppDispatch: () => mockDispatch,
}));

步骤2:在测试用例中断言dispatch的调用

渲染组件后,直接断言mockDispatch的调用情况:

it("验证resetStates action是否被dispatch", async () => {
  // 渲染组件
  render(<MockForgeViewer />);

  // 如果dispatch是同步触发的,直接断言
  expect(mockDispatch).toHaveBeenCalledWith(resetStates());

  // 如果dispatch是异步操作后触发的,用waitFor等待断言条件满足
  await waitFor(() => {
    expect(mockDispatch).toHaveBeenCalledWith(resetStates());
  });
});

关键说明

  • 通过vi.mock替换useAppDispatch,确保组件中调用const dispatch = useAppDispatch()时,拿到的是我们的mockDispatch函数。
  • 可以通过mockDispatch的API(比如toHaveBeenCalledTimes、toHaveBeenLastCalledWith)做更细致的断言,比如检查调用次数、具体参数等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 19:57:10