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

TypeScript构造函数报错:TypeError: MainApp_1.MainApp不是构造函数

报错原因及解决方案

TypeError: MainApp_1.MainApp is not a constructor 报错的核心是代码运行时导入的MainApp不是预期的类构造函数,通常为undefined或其他非函数类型,按优先级排查以下问题即可解决:

  • 路径或模块导出导入不匹配
    首先确认MainApp.ts和Smoke.ts的相对路径正确,文件大小写和路径拼写完全一致。如果你的TS编译配置(tsconfig.json)开启了CommonJS模块转换,ES模块的命名导出可能会被挂载到default属性上,导致命名导入拿到undefined,可以调整导入写法做兼容:
    import * as MainAppModule from "./MainApp";
    const MainApp = MainAppModule.MainApp || MainAppModule.default;
    
  • 全局依赖缺失导致类导出异常
    你在MainApp的login方法中直接使用了TestCafe的全局t对象,类初始化阶段如果检测到未定义的全局依赖,会导致类导出失败。建议把t改成参数传入,避免依赖全局变量:
    修改MainApp.ts代码:
    import type { TestController, ClientFunction } from "testcafe";
    const getUrl = ClientFunction(() => window.location.href);
    
    export class MainApp {
      async login(t: TestController, url:string) {
        await t.expect(getUrl()).eql(url);
      }
    }
    
    调用时传入当前测试上下文的t:
    await mainApp.login(t, testUrl);
    
  • 实例化时机错误
    你当前在fixture定义外层直接实例化MainApp,TestCafe的测试文件执行顺序可能会导致实例化时类还未完成加载,可以把实例化操作移到beforeEach钩子内部:
    import { MainApp } from "./MainApp";
    const testUrl = `https://www.google.com/`;
    let mainApp: MainApp;
    
    fixture("fixture")
      .page("https://www.google.com/")
      .beforeEach(async (t) => {
        mainApp = new MainApp();
        console.log("test");
      })
      .disablePageCaching("fixture");
    
  • 语法错误导致编译产物异常
    你提供的Smoke.ts代码中test函数没有补全闭合的})符号,如果实际运行的代码也存在语法缺失,会导致TS编译后的产物异常,导出的类不符合预期,请先补全所有语法闭合符号。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 19:15:00