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

WebdriverIO类继承报错:TypeError: Class extends value undefined is not a constructor or null

解决WebdriverIO中类继承构造函数报错问题

错误原因

基类最后一行导出的是BaseComponent的实例对象,而非类本身:

module.exports = new BaseComponent();

子类CardComponent试图extends一个实例对象(而非构造函数),违反类继承语法要求,直接抛出TypeError: Class extends value undefined is not a constructor or null。

修复方案

1. 修正基类导出方式

将基类的导出改为类本身,让子类能正确继承构造函数:

class BaseComponent {   
    constructor(rootSelector){
        this.rootSelector = rootSelector;
    }

    get rootElement(){        
        return $(this.rootSelector);
    }
}
// 导出类,而非实例
module.exports = BaseComponent;

2. 修正子类的继承与实例化

子类正常继承基类,构造函数通过super传递根选择器,最后导出子类实例:

const BaseComponent = require('../common/base.component');

class CardComponent extends BaseComponent{   
    constructor(){
        // 调用父类构造函数,传入当前组件的根选择器
        super(`//div[@id='tbodyid']`);
    }

    productLinkText(productName){                
        return this.rootElement.$(`//a[contains(text(),'${productName}')]`);
    }
}
// 导出子类实例供测试使用
module.exports = new CardComponent();

核心需求满足说明

修改后:

  • 根元素的定义逻辑(rootSelector存储、rootElement获取)完全复用基类代码
  • 子类仅需在构造函数中传入自身的根选择器,实现组件逻辑的分层与复用
  • 跨文件的类继承可以正常运行,和同一文件内的效果一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 11:23:12