我们如何在量角器中单击特定文本的父元素

How can we click on a parent element of a particular text in protractor

我们的 UI 代码如下。

<div _ngcontent-wuu-c29="" class="frx-rule-block ng-star-inserted">
   <div _ngcontent-wuu-c29="" class="frx-rule-header">
      <h4 _ngcontent-wuu-c29="">1</h4>
      <i _ngcontent-wuu-c29="" class="demo-icon"></i>
      <label _ngcontent-wuu-c29="" class="frx-rule-title">Rule Group</label>
   </div>
   <div _ngcontent-wuu-c29="" class="frx-rule-body">
      <div _ngcontent-wuu-c29="" class="frx-rule-descr">
          <h3 _ngcontent-wuu-c29="">Sample rule groups</h3>
          <p _ngcontent-wuu-c29="">Sample description.</p>
      </div>
      <div>--------</div>
   </div>
</div>

我们有一个主要 div 并且在这个主要 div 内部我们有许多子 class 元素 "frx-rule-block ng-star-inserted" as given above.The text "Sample rule groups" 在 h3 标签中在不同的“.frx-rule-block ng-star-inserted”中是不同的。我需要点击这个特定 h3 标签的 h4 标签中的数字 1(这个数字每次都在变化,所以我无法指定哪个是 h4 标签内的文本)。那么我如何 select 这个特定的文本 "Sample rule groups" 然后点击 h4 tag.Thanks 提前。

有一种方法可以通过 xpath select 兄弟元素,但我不记得了。所以这里有一个解决方法:

let myElement = element(by.cssContainingTex(".frx-rule-title", "Rule Group").element(by.xpath("..")).element(by.xpath("//h4[contains(text(), '1')]"))

简答

let h4ByText = (text) => element(by.xpath(`//*[@class="frx-rule-body"]//h3[contains(text(),"${text}")]//ancestor::div[contains(@class,"frx-rule-block")]//h4`));

如果你不明白它是如何工作的,lmk我会给你完整的答案

我根本不喜欢使用 xpath,所以我会这样做。这样做肯定需要更多的代码和工作,但我不惜一切代价避免使用 xpath。个人喜好而已。

const match = 'Sample rule groups';

// get all blocks 
const ruleblocks = element.all(by.css('.frx-rule-block'));

// find the one that contains the header you want
const relevantBlock = await ruleblocks.filter(block => {
  const ruleBodyHeader = block.$('.frx-rule-body > h3');

  return ruleBodyHeader.getText().then(text => {
    return text === match;
  }
}).first();

const ruleHeader = relevantBlock.$('.frx-rule-header > h4');
await ruleHeader.click();