首页 > 解决方案 > 如何使用 XPath 或 CSS 选择器在 Nightwatch 测试中查找子字符串

问题描述

我必须对以下元素进行 Nightwatch 测试:

<textarea id="xxxxxxxx-971-condition" 
   type="text" placeholder="Enter condition" 
   required="required" aria-required="true" class="form-control">

这基本上很容易,除了我发现“-971-”或多或少是一个随机的 3 位数字,因为 textarea 可以在页面上显示多次。我不能简单地查找“starts-with('xxxxxxxx-')”,因为还有许多其他表单字段共享该前缀。出于同样的原因,我不能或多或少地使用“ends-with('-condition')”。我需要将两者结合起来。但是怎么做?这是我尝试过的,首先从简单的案例开始:

browser
  .useXpath() // every selector now must be xpath
  .assert.visible("//textarea[ends-with(@id,'-condition')]") FAILS!
  .assert.visible("//textarea[@id[ends-with(text(),'-condition')]]") FAILS!
  .assert.visible("//textarea[@id=[ends-with(text(),'-condition')]]") FAILS!
  .assert.visible("//textarea[contains(@id, starts-with(text(),'xxxxxxxx-') and ends-with(text(),'-condition'))]") FAILS!
  .assert.visible("//textarea[contains(@id, starts-with(text(),'xxxxxxxx-'))]") FAILS!
  .assert.visible("//textarea[contains(@id, ends-with(text(),'-condition'))]") FAILS!
  .assert.visible("//id[contains(., ends-with(text(),'-condition'))]") FAILS!
  .assert.visible("//textarea[@id[contains(., ends-with(text(),'-condition'))]]") FAILS!
  .assert.visible("//textarea[@id[contains(., starts-with(text(),'xxxxxxxx-'))]]") FAILS!

  .useCss() // we're back to CSS now
  .assert.visible("textarea[id^='xxxxxxxx-']")  <==== THIS WORKS!!!!
  .assert.visible("textarea[id$='-condition']")  <==== THIS WORKS!!!!
  .assert.visible("textarea[id^='xxxxxxxx-' and id$='-condition']") <==== together this does NOT work

由于测试在进入本节之前运行了相当长的一段时间,因此我有很多时间去谷歌搜索。此外,您会注意到我使用 CSS 选择器的运气要好得多(但无法将它们组合成我需要的效果)。

有人有建议吗?

标签: xpathcss-selectorsnightwatch

解决方案


textarea[id^='xxxxxxxx-' and id$='-condition']不起作用的原因是因为您暗示该元素包含 2 个不同的 ID 属性。

我相信这应该有效:

textarea[id^='xxxxxxxx-'][id$='-condition']

推荐阅读