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

如何使用Jest测试接收dispatch的柯里化useReducer辅助函数

如何测试单行柯里化的makeReducerSetState函数?

我编写了如下单行柯里化函数:

export const makeReducerSetState = dispatch => type => payload =>
  dispatch({ type, payload });

该函数在使用useReducer的自定义钩子中按如下方式调用:

const wrapReducerDispatch = makeReducerSetState(stateDispatch);
const setSelectedSteps = wrapReducerDispatch(
  EDITION_MODAL_REDUCER_TYPES.SET_SELECTED_STEPS
);

之后通过如下方式触发action:

const handleNext = useCallback(() => {
    setSelectedSteps({
      selectedIndex: selectedStep.selectedIndex + 1,
    });
  }, [selectedStep]);

我不清楚如何使用Jest测试这个单行柯里化函数,查阅相关资料未找到类似案例,希望得到指导。


测试方案

核心思路是用Jest的mock函数模拟dispatch,分阶段验证柯里化函数的每一层调用是否符合预期:

  • 创建mock dispatch函数:用jest.fn()生成mock函数,追踪调用情况与参数。
  • 分阶段调用柯里化函数:依次调用三层函数,可单独验证每一层,也可直接走完整流程验证最终结果。

完整测试代码示例

import { makeReducerSetState } from './your-file-path';

describe('makeReducerSetState', () => {
  it('dispatches correct action with specified type and payload', () => {
    // 初始化mock dispatch
    const mockDispatch = jest.fn();
    const testActionType = 'TEST_SET_SELECTED_STEPS';
    const testPayload = { selectedIndex: 2 };

    // 逐层调用柯里化函数
    const wrapDispatch = makeReducerSetState(mockDispatch);
    const setActionCreator = wrapDispatch(testActionType);
    setActionCreator(testPayload);

    // 验证dispatch调用情况
    expect(mockDispatch).toHaveBeenCalledTimes(1);
    expect(mockDispatch).toHaveBeenCalledWith({
      type: testActionType,
      payload: testPayload
    });
  });

  it('returns functions at each curried layer', () => {
    const mockDispatch = jest.fn();
    const wrapDispatch = makeReducerSetState(mockDispatch);
    
    // 验证第一层调用返回函数
    expect(typeof wrapDispatch).toBe('function');
    
    // 验证传入type后仍返回函数
    const setActionCreator = wrapDispatch('TEST_TYPE');
    expect(typeof setActionCreator).toBe('function');
  });
});

测试要点

  1. 验证柯里化结构:确保每一层调用都返回函数,保证函数的柯里化设计符合预期。
  2. 验证参数准确性:确认最终传递给dispatch的type和payload与传入值完全一致,无篡改。
  3. 利用mock追踪:通过Jest mock函数的toHaveBeenCalledTimes和toHaveBeenCalledWith方法,精准验证函数行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:15:58