如果相同的元素可能因不同 ID或名称而改变,这取决于很多因素,我可以准确地对此元素进行断言
Doest nighwatchjs允许根据SAHI这样的相对位置做出断言吗? (这个元素的左边......,在div之下等等)
我想避免使用Xpath解决方案,它基于元素类型(div,id,name等),如果我将其设置为所有类型:
//*[contains(text(),'hello world')]
我会多次出现,无法知道我试图断言哪一个。
例如:在同一页面上运行相同的测试,即使div id发生变化或其他元素,我也能找到这个“hello world”。
<div id="homebutton">
<p>
<a href=#>
<span name="hm">Home</span>
<a>
</p>
</div>
<div id=[0-9]>
<p>
<a href=#>
<span name="hw">hello world</span>
<a>
</p>
</div>
[...]
<div id=[0-9]>
<p>
<a href=#>
<span name="hw">hello world</span>
<a>
</p>
</div>
<div id="logoutbutton">
<p>
<a href=#>
<span name="lo">Logout</span>
<a>
</p>
</div>
测试示例: Assert元素包含字符串“hello world”,不是那个靠近注销按钮但是靠近主页按钮 的
答案 0 :(得分:1)
扩展我以前的答案,你有两个选择,如果你想要的Hello World是*总是倒数第二,出现在Logout按钮之前然后你想要一个类型的倒数第二个,你可以使用xPath像这样的选择器:
"//*[.='hello world'][last()-1]"
我与你分享的Rosetta文档中的权利,所以你应该知道现在
另一种选择是获得所有比赛的集合。为此,我写了一个像这样的辅助函数:
module.exports = {
getCountOfElementsUseXpath : function (client, selector, value) {
// set an empty variable to store the count of elements
var elementCount;
// get a collection of all elements that match the passed selector
client.getEls(selector, function(collection) {
// set the variable to be that collection's length
elementCount = collection.length;
// log the count of elements to the terminal
console.log("There were " + elementCount + " question types")
return elementCount;
});
},
};
然后你可以使用一些公式来表明你的选择器距离最后一个元素的距离。
答案 1 :(得分:0)
xpath选择器"//div[contains(text(), 'hello world')]"
将匹配您显示的两个元素。如果元素本身可以更改,则使用通配符:"//*[contains(text(), 'hello world')]"
对于具有该确切文本的任何元素的匹配:
"//*[.='hello world']"
A great source, a "Rosetta stone", for selector construction
使用带有夜间守卫的xpath选择器:
"some test": function(client){
client
.useXpath().waitForElementPresent("//div[contains(text(), 'hello world')]", this.timeout)
}
答案 2 :(得分:0)
Xpath解决方案没问题,但这是我需要的解决方案,更通用,并提供更多选项:
使用elements并设法返回子项目元素数组
我选择返回符合我需要的数据对象数组:
[{id: webElementId ,尺寸:{width: 18 ,身高: 35 },...},{id: webElementId ,...}等等。
有了这些信息,我可以做很多事情:
查找具有特定文本,属性或css属性的元素 对其执行任何操作,例如断言或通过计算其大小来点击其右侧。
鼠标悬停匹配的每个元素(如果要浏览标签 子菜单ul li / ol li)
填充了更多数据,您可以执行更多的断言。