TestCafe中选择器存在性判断失效问题求助
问题原因及解决办法
你的问题出在TestCafe中t.expect(...).ok()的返回值特性上:
不管断言成功(元素存在)还是失败(元素不存在),t.expect(...).ok()都会返回一个包含断言结果的对象,而不是布尔值。当你把这个对象直接作为if条件时,它会被JavaScript视为真值,所以不管元素是否存在,if代码块都会执行。
两种正确的写法:
- 获取断言结果的
passed属性判断
const dropdownCheckResult = await t.expect(this.dynamicButtonDropdownByAttribute('originator-org-select-button').exists).ok(); if (dropdownCheckResult.passed) { await this.selectValueInDropdownByAttribute('originator-org-select-button' , 'ORG') await this.clickButtonByAttribute('originator-org-next-button') }
- 直接判断元素的
exists属性(更简洁)
if (await this.dynamicButtonDropdownByAttribute('originator-org-select-button').exists) { await this.selectValueInDropdownByAttribute('originator-org-select-button' , 'ORG') await this.clickButtonByAttribute('originator-org-next-button') }
第二种方式跳过了断言步骤,直接获取元素是否存在的布尔值,更适合做条件判断场景。
内容的提问来源于stack exchange,提问作者user19761491
相关产品推荐
相关产品推荐

