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

React测试时遇TypeError: handleFilter is not a function错误求解决方案

React子组件传参给父组件测试报错:TypeError: handleFilter is not a function

你的问题核心是测试用例中未正确为子组件传入handleFilterValue函数类型的props,导致子组件调用时触发类型错误。先修正代码里的拼写问题,再针对性调整测试用例即可解决。

第一步:修正组件代码的拼写问题

你的代码里存在两处拼写错误,虽运行时可能不影响,但会增加排查难度:

  • 子组件名称:ChildComponenet → ChildComponent
  • 函数名称:applyFIlters → applyFilters

修正后的组件代码:

const ParentComponent = () => {
    const getFilterValue = (filter:string) => {
        setFilter(filter);
    };

    return (
        <ChildComponent handleFilterValue={getFilterValue} />
    )
}

// 修正拼写后的子组件
const ChildComponent = ({handleFilterValue}: { handleFilterValue: (filter: string) => void }) => {  
    const applyFilters = () => {
        // 假设这里有逻辑生成filter值
        const filter = "test-filter";
        handleFilterValue(filter);
    }

    return (
        <button onClick={applyFilters}>应用筛选</button>
    )
}

注:替换了any类型为明确的props类型约束,能在编译阶段提前发现类型问题

第二步:修复测试用例

报错的根本原因是测试时渲染子组件未传入handleFilterValue props,或者传入的不是函数。以下是React Testing Library的示例测试代码:

import { render, screen, fireEvent } from '@testing-library/react';
import ChildComponent from './ChildComponent';

test('点击应用筛选按钮时调用handleFilterValue', () => {
    // 创建一个模拟函数,用于追踪调用情况
    const mockHandleFilter = jest.fn();
    
    // 渲染子组件时必须传入所需的props
    render(<ChildComponent handleFilterValue={mockHandleFilter} />);
    
    // 触发applyFilters的操作(比如点击按钮)
    const applyButton = screen.getByRole('button', { name: /应用筛选/i });
    fireEvent.click(applyButton);
    
    // 验证模拟函数是否被正确调用
    expect(mockHandleFilter).toHaveBeenCalledWith("test-filter");
});

关键注意事项

  • 测试子组件时,必须模拟所有依赖的props,尤其是函数类型的props,不能省略
  • 避免使用any类型,明确的类型定义能帮助你在开发阶段发现潜在错误
  • 检查测试用例中是否有拼写错误,比如误将handleFilterValue写成handleFilter(报错信息里的handleFilter可能是测试里的拼写问题)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 20:23:26