如何测试HOC内部函数update是否被传入正确props调用?
问题分析与解决方案
一、原代码的语法错误
首先你的组件代码存在两处基础语法问题,这是导致测试异常的前提原因:
- 函数导出语法错误:
export const function update是无效写法,正确格式应为export function update(props)或箭头函数形式export const update = (props) => {} - 未定义渲染组件:
withUpdatedProps中使用的WrappedComponent从未声明,应替换为传入的element参数
二、测试失败的核心原因
- 拼写错误:测试代码中
TestCompnent.defaultProps应为TestComponent.defaultProps,拼写错误导致默认props未正确绑定 - 默认props未传递:你给
TestComponent设置了defaultProps,但withUpdatedProps返回的Wrapper组件并未继承这些默认props,渲染<UpdatedTestComponent/>时,Wrapper接收的props是空对象,因此update被调用时传入的是空对象而非你期望的默认值 - 模块导出异常:原组件的语法错误导致
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
相关产品推荐
相关产品推荐

