求助排查:Cannot read property 'keyboard' of undefined报错
解决“Cannot read property 'keyboard' of undefined”错误
你遇到的错误根源是:SearchPage类中的searchKeyboard属性仅声明了类型,但从未被实例化为SearchKeyboardModel的对象,导致this.searchKeyboard的值为undefined,自然无法读取它的keyboard属性。
修复方案
只需在SearchPage中完成searchKeyboard的实例化即可,有两种实现方式:
方式1:在构造函数中实例化
class SearchPage extends BasePage { searchKeyboard: SearchKeyboardModel; constructor() { super(); // 实例化SearchKeyboardModel对象 this.searchKeyboard = new SearchKeyboardModel(); } async enterSearchKeyword(keyword: string) { await t.expect(this.searchKeyboard.keyboard.visible).ok({ timeout: 3000 }); } }
方式2:直接在属性声明时实例化
class SearchPage extends BasePage { // 直接初始化实例 searchKeyboard: SearchKeyboardModel = new SearchKeyboardModel(); constructor() { super(); } async enterSearchKeyword(keyword: string) { await t.expect(this.searchKeyboard.keyboard.visible).ok({ timeout: 3000 }); } }
实例化后,this.searchKeyboard会成为SearchKeyboardModel的有效对象,其keyboard属性会被正确初始化为目标选择器,后续访问this.searchKeyboard.keyboard.visible就不会再触发undefined相关错误。
内容的提问来源于stack exchange,提问作者BruceyBandit
相关产品推荐
相关产品推荐

