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

升级Node14至Node18后执行npm test出现TypeError问题求助

解决Node18升级后TypeError: (0, _MyApp.getDataInfo) is not a function测试报错

具体报错信息

node:internal/process/promises:288 
          triggerUncaughtException(err, true /* fromPromise */); 
TypeError: (0, _MyApp.getDataInfo) is not a function

执行npm test时触发,环境:npm 8.19.2、Node.js v18.12.1、jest ^28.1.1、react-scripts ^5.0.0,由Node14升级到Node18后出现,已尝试async/await无效。


解决步骤

  • 检查模块导出与导入的匹配性
    Node18对ES模块的语法校验更严格,之前Node14兼容的不规范导入导出现在会触发错误:

    • 若MyApp中getDataInfo是命名导出(export const getDataInfo = () => {}),导入必须用import { getDataInfo } from './MyApp';
    • 若为默认导出(export default getDataInfo),导入要改为import getDataInfo from './MyApp';
    • 同时确认package.json中"type"字段:如果设为"module",需统一使用ES模块语法(不能混用module.exports/require),反之则保持CommonJS语法一致。
  • 清除Jest缓存
    旧缓存可能保留了Node14时代的模块解析结果,执行以下命令清除:

    npm test -- --clearCache
    
  • 排查模块Mock问题
    检查测试文件中是否对MyApp模块做了Mock:

    • 若存在jest.mock('./MyApp'),需确保Mock对象正确导出getDataInfo函数,示例:
      jest.mock('./MyApp', () => ({
        getDataInfo: jest.fn(() => Promise.resolve({ /* 模拟返回数据 */ }))
      }));
      
    • 避免意外自动Mock本地模块,可在Jest配置中调整automock为false(仅针对eject后的项目)。
  • 检查Jest与Babel配置兼容性

    • 若为eject后的项目,确认jest.config.js中moduleFileExtensions包含js、jsx,transform配置正确使用babel-jest;
    • 若自定义了Babel配置,@babel/preset-env的targets需设置为node: '18',确保编译后的代码适配Node18环境。
  • 清理依赖冲突
    多个Jest版本可能导致解析异常,执行以下步骤重置依赖:

    rm -rf node_modules package-lock.json
    npm install
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 14:12:21