Nightwatch中.assert.containsText()针对第3个rect:nth-child元素不生效问题
Nightwatch 第n个rect元素断言失败解决方案
问题复现代码
browser.execute(function () { document.getElementsByClassName('vitara-point')[1].innerHTML = 'bar2' }).assert.containsText('rect:nth-child(2)', 'bar2').moveToElement('rect:nth-child(2)', 2, 2).click('rect:nth-child(2)').pause(2000) //bar3 //browser.execute(function(){document.getElementsByClassName('vitara-point')[2].innerHTML = 'bar3'}).assert.containsText('rect:nth-child(3)', 'bar3').moveToElement('rect:nth-child(3)', 2,2).click('rect:nth-child(3)').pause(2000)
故障原因
nth-child计数规则导致选择器匹配错误:nth-child是统计父元素下所有子元素的排序,而非仅统计rect标签的元素,如果第3位的子元素是其他标签,rect:nth-child(3)就匹配不到目标元素- 断言超时时间不足:第3个及后续元素的渲染、文本更新耗时比第2个元素长,默认5s超时无法覆盖更新周期
- 代码逻辑未生效:你提供的代码中bar3相关的修改、断言逻辑全被注释,运行时自然不会执行对应的innerHTML修改操作,断言必然失败
解决方法
- 修正元素选择器
将rect:nth-child(n)替换为rect:nth-of-type(n),该选择器只会统计同标签的rect元素排序,避免其他标签元素干扰计数,示例:
.assert.containsText('rect:nth-of-type(3)', 'bar3')
- 延长断言超时时间
可以先等待目标元素加载完成,再执行断言,也可单独为断言设置更长的超时时间,示例:
.waitForElementPresent('rect:nth-of-type(3)', 10000) // 超时设为10s .execute(function () { document.getElementsByClassName('vitara-point')[2].innerHTML = 'bar3' }) // 给containsText单独设置10s超时,第四个参数为超时配置 .assert.containsText('rect:nth-of-type(3)', 'bar3', '第3个rect文本校验通过', 10000)
- 封装批量逻辑适配n个元素测试
如果需要处理后续多个元素的测试,直接封装循环逻辑,避免重复编码:
// 可自定义测试的元素总数,比如测试到第10个就赋值为10 const totalTestCount = 10 for(let i = 1; i < totalTestCount; i++) { const targetText = `bar${i+1}` browser.execute(function (index, text) { document.getElementsByClassName('vitara-point')[index].innerHTML = text }, [i, targetText]) .waitForElementPresent(`rect:nth-of-type(${i+1})`, 10000) .assert.containsText(`rect:nth-of-type(${i+1})`, targetText, 10000) .moveToElement(`rect:nth-of-type(${i+1})`, 2, 2) .click(`rect:nth-of-type(${i+1})`) .pause(2000) }
- 运行前确认对应测试逻辑的注释已取消,确保修改innerHTML的代码能正常执行。
内容的提问来源于stack exchange,提问作者Dhanashri Sakharkar
相关产品推荐
相关产品推荐

