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

如何测试HOC内部函数update是否被传入正确props调用?

问题分析与解决方案

一、原代码的语法错误

首先你的组件代码存在两处基础语法问题,这是导致测试异常的前提原因:

  1. 函数导出语法错误:export const function update 是无效写法,正确格式应为 export function update(props) 或箭头函数形式 export const update = (props) => {}
  2. 未定义渲染组件:withUpdatedProps 中使用的 WrappedComponent 从未声明,应替换为传入的 element 参数

二、测试失败的核心原因

  1. 拼写错误:测试代码中 TestCompnent.defaultProps 应为 TestComponent.defaultProps,拼写错误导致默认props未正确绑定
  2. 默认props未传递:你给TestComponent设置了defaultProps,但withUpdatedProps返回的Wrapper组件并未继承这些默认props,渲染<UpdatedTestComponent/>时,Wrapper接收的props是空对象,因此update被调用时传入的是空对象而非你期望的默认值
  3. 模块导出异常:原组件的语法错误导致update函数无法被Jest正确spy,进而无法追踪调用情况

三、修正后的组件代码

// updateProps.jsx
export function update(props) {
  // 你的业务逻辑代码
  return props;
}

export function withUpdatedProps(element) {
  const Wrapper = (props) => {
    const updatedProps = update(props);
    // 使用传入的element作为要渲染的目标组件
    return <element {...updatedProps} />;
  };

  // 让Wrapper继承原组件的defaultProps,确保默认值能传递到update函数
  Wrapper.defaultProps = element.defaultProps;

  return Wrapper;
}

四、修正后的测试代码

import * as updateProps from './updateProps';
import { render } from '@testing-library/react';

const TestComponent = () => <p>Hello World!</p>;

// 修正拼写错误,绑定默认props
TestComponent.defaultProps = { color: "red" };

const withUpdatedProps = updateProps.withUpdatedProps;

describe("updateProps", () => {
  it("调用update时传入正确的默认props", () => {
    // 在创建组件前就创建spy,确保能捕获到调用
    const updateSpy = jest.spyOn(updateProps, 'update').mockImplementation(props => props);
    
    const UpdatedTestComponent = withUpdatedProps(TestComponent);
    
    render(<UpdatedTestComponent/>);

    // 此时update会接收到TestComponent的defaultProps
    expect(updateSpy).toHaveBeenCalledWith(TestComponent.defaultProps);
    
    // 清理spy,避免影响其他测试
    updateSpy.mockRestore();
  });
});

关键说明

  • 给Wrapper组件添加defaultProps继承逻辑,确保原组件的默认参数能传递到update函数
  • 修正所有拼写和语法错误,保证模块能正常导出、组件能正常渲染
  • 在创建包裹组件前就初始化spy,确保不会错过update的调用时机

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 07:47:11