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

组件作用域内测试自定义Hook触发TypeError: not a function问题求助

解决TypeError: (0 , _fileName.useCustomHook) is not a function的方案
  • 检查自定义Hook的导出与导入匹配性
    确认Hook的导出类型(默认导出/命名导出)和组件中的导入方式完全一致:

    • 若Hook是export default useCustomHook,组件需用import useCustomHook from './fileName'
    • 若Hook是export const useCustomHook = () => {},组件需用import { useCustomHook } from './fileName'
      同时清理Next.js和Node的缓存:
    rm -rf .next node_modules/.cache
    npm install
    npm run test
    
  • 排查测试中的Mock冲突
    检查测试文件是否存在全局Mock或文件级Mock意外覆盖了该Hook。如果需要显式Mock,可使用如下写法保留原模块其他导出:

    jest.mock('../path/to/yourHookFile', () => ({
      ...jest.requireActual('../path/to/yourHookFile'),
      useCustomHook: jest.fn(() => ({ /* 填入Hook的模拟返回值 */ }))
    }))
    
  • 验证依赖兼容性与重装依赖
    尽管版本理论兼容,仍可能存在锁文件异常。删除锁文件并重装依赖:

    rm -rf package-lock.json node_modules
    npm install
    

    确保@testing-library/react和@testing-library/react-hooks的版本适配React 17:当前使用的v12和v8版本是兼容的,无需升级。

  • 处理Next.js专属模块解析问题

    • 若自定义Hook依赖Next.js API(如useRouter),需在测试中对应Mock:
      jest.mock('next/router', () => ({
        useRouter: jest.fn(() => ({ pathname: '/' }))
      }))
      
    • 尝试将组件导入改为完整相对路径,避免Next.js模块解析歧义。
  • 禁用Jest缓存
    Jest的模块缓存可能导致旧代码残留,运行测试时添加--no-cache参数:

    npm run test -- --no-cache
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 04:40:29