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

React v16.13.1下用Jest和React Testing Library测试Redux Thunk异步dispatch

Redux Thunk异步dispatch逻辑单元测试实现方案

核心思路是通过Jest Mock能力模拟UserService的请求返回,分别覆盖请求成功、请求失败两个场景即可覆盖所有代码分支。


前置操作:Mock外部依赖

在测试文件开头模拟UserService模块,避免测试时触发真实网络请求:

// 替换为你实际的UserService文件相对路径
import * as UserService from './userService';
jest.mock('./userService');

测试用例1:请求成功场景

覆盖try块、finally块逻辑,验证正常返回时的dispatch顺序:

it('dispatches correct actions when getUser request succeeds', async () => {
  const dispatch = jest.fn();
  // 模拟接口返回的用户数据
  const mockUserList = [{ id: 1, name: '测试用户' }];
  UserService.getUser.mockResolvedValue(mockUserList);

  await loadUsers()(dispatch);

  // 按调用顺序校验dispatch参数
  expect(dispatch).toHaveBeenNthCalledWith(1, userRequest());
  expect(dispatch).toHaveBeenNthCalledWith(2, userLoading());
  expect(dispatch).toHaveBeenNthCalledWith(3, userSuccess(mockUserList));
});

测试用例2:请求失败场景

覆盖catch块、finally块逻辑,验证请求异常时的dispatch顺序:

it('dispatches correct actions when getUser request fails', async () => {
  const dispatch = jest.fn();
  // 模拟接口返回的错误信息
  const mockRequestError = new Error('用户接口请求失败');
  UserService.getUser.mockRejectedValue(mockRequestError);

  await loadUsers()(dispatch);

  // 按调用顺序校验dispatch参数
  expect(dispatch).toHaveBeenNthCalledWith(1, userRequest());
  expect(dispatch).toHaveBeenNthCalledWith(2, userError(mockRequestError));
  expect(dispatch).toHaveBeenNthCalledWith(3, userSuccess(null));
});

额外提示:你当前贴出的UserService代码存在笔误,定义了USERS_ENDPOINT常量但调用axios.get时使用了未声明的PRODUCTS_ENDPOINT,建议修正避免运行报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 18:15:02