Karate中如何获取带important类父元素的背景色?
解决方法:检查带
important类的父元素背景色 原始HTML结构
<div class="react-data-field separated-area case-overview-field-root important"> <div class="row"> <div class="col-xs-6"> <div class="data-label">Test is important</div> </div> <div class="col-xs-6"><div class="data-value"> <div class="easy-edit-wrapper">Click to edit</div> </div> </div> </div>
原匹配代码(无法获取正确背景色)
* match script("//div[text()='Test - is important']", "function(e){ return getComputedStyle(e)['background-color']}") == "#7d7d80"
问题说明
当前代码定位的是文本Test - is important所在的div,但背景色样式实际定义在带有important类的父级div上,所以需要修改代码定位到这个父元素再获取背景色。
两种可行修改方案
方案一:用XPath的
ancestor轴直接定位父元素
修改XPath路径,从文本所在div向上找到带important类的父div:* match script("//div[text()='Test is important']/ancestor::div[contains(@class, 'important')]", "function(e){ return getComputedStyle(e)['background-color']}") == "#7d7d80"注:注意修正XPath里的文本内容,和HTML里的
Test is important保持一致,避免匹配失败。方案二:在回调函数中用
closest()查找父元素
保持XPath定位到文本div,在函数内部通过DOM方法找到最近的目标父元素:* match script("//div[text()='Test is important']", "function(e){ return getComputedStyle(e.closest('.important'))['background-color']}") == "#7d7d80"closest('.important')会从当前元素向上遍历,返回第一个匹配.important选择器的祖先元素,以此获取正确的背景色。
内容的提问来源于stack exchange,提问作者Andrei Vartic
相关产品推荐
相关产品推荐

