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
相关产品推荐
相关产品推荐

