求助:解决测试代码中Cannot read property 'SearchedClinic' of undefined错误
问题分析与解决方案
这个错误的核心原因是Promise回调函数里的this指向不对——在then()的普通函数回调中,this不再指向你的类实例,而是变成了undefined(严格模式下),所以自然找不到this.SearchedClinic。
下面给你三种可行的解决方法,按推荐程度排序:
方法1:使用ES6箭头函数(最简洁)
箭头函数不会创建自己的this,它会继承外层作用域的this,完美解决上下文丢失问题:
public SearchAndSelectClinicA(SearchName:string){ this.ClinicSearch.sendKeys(SearchName); this.SearchIcon.click(); // 改用箭头函数,this会指向类实例 this.SearchedClinic.count().then((count) => { if(count>1){ // 这里的this也能正确访问类的属性 this.SearchedClinic.each((rows)=>{ rows.getText().then((value)=>{ // 注意:原判断有逻辑问题,indexOf找不到返回-1会被判定为true,这里修正为>-1 if(value.indexOf(SearchName) > -1){ rows.click(); } }); }); } }); }
另外提个小细节:原代码里的if(value.indexOf(SearchName))判断存在逻辑漏洞——indexOf找不到匹配时返回-1,而-1在布尔判断里是true,会导致不该点击的元素也被触发。如果你的环境支持ES6,也可以用更直观的value.includes(SearchName)来做判断。
方法2:提前保存this到变量
如果你的环境不支持ES6箭头函数,可以在进入Promise回调前,把类实例的this存到一个变量(比如that或self),然后在回调里用这个变量访问属性:
public SearchAndSelectClinicA(SearchName:string){ const that = this; // 保存当前的this指向 this.ClinicSearch.sendKeys(SearchName); this.SearchIcon.click(); this.SearchedClinic.count().then(function(count){ if(count>1){ // 用that代替this访问类属性 that.SearchedClinic.each(function(rows){ rows.getText().then(function(value){ if(value.indexOf(SearchName) > -1){ rows.click(); } }); }); } }); }
方法3:用bind()绑定this
可以通过bind()方法把回调函数的this强制绑定到类实例上:
public SearchAndSelectClinicA(SearchName:string){ this.ClinicSearch.sendKeys(SearchName); this.SearchIcon.click(); // 绑定this到回调函数 this.SearchedClinic.count().then(function(count){ if(count>1){ this.SearchedClinic.each(function(rows){ rows.getText().then(function(value){ if(value.indexOf(SearchName) > -1){ rows.click(); } }); }); } }.bind(this)); // 这里绑定this到回调函数 }
内容的提问来源于stack exchange,提问作者DtestA
相关产品推荐
相关产品推荐

