nightwatchjs 能否基于引用准确地执行断言?

Can nightwatchjs perform an assertion based on a reference with accuracy?

相同 元素可能因 不同 id 或名称而变化的情况下,取决于许多因素,我将能够准确断言此元素。

nighwatchjs 是否允许像 SAHI 那样基于相对位置进行断言? (这个元素的左边...,下一个div,等等)

我想避免 Xpath 解决方案,它基于元素类型(div、id、名称等),如果我将其设置为所有类型:

//*[contains(text(),'hello world')]

我会遇到很多次,但无法知道我要断言的是哪一个。

e.g : Running the same test on the same page, I would be able to find this "hello world" even if the div id changes or another element.

<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>

Test example : Assert element containing string "hello world", not the one which is near the logout button but the one which is near the home button.

xpath 选择器"//div[contains(text(), 'hello world')]" 将匹配您显示的两个元素。如果元素本身可以更改,您可以使用通配符:"//*[contains(text(), 'hello world')]"

对于具有该确切文本的任何元素的匹配:

"//*[.='hello world']"

A great source, a "Rosetta stone", for selector construction

要在 nightwatch 中使用 xpath 选择器:

"some test": function(client){
client
    .useXpath().waitForElementPresent("//div[contains(text(), 'hello world')]", this.timeout)
}

扩展我之前的回答,你有两个选择,如果你想要的 Hello World *总是倒数第二个,出现在注销按钮之前,那么你想要倒数第二个类型,你可以使用像这样的 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;        
        });
    },

};

然后您可以使用它和一些公式来计算您的选择器与最后一个元素的距离。

Xpath 解决方案没问题,但这是我需要的解决方案,更通用并提供更多选项:

使用 elements 并设法 return 一个子元素数组

我选择 return 一组对象,其数据符合我的需要:

[{ id: webElementId, size: {width: 18, height: 35}, ...}, {id: webElementId, ...}, etc.]

有了这些信息,我可以做很多事情:

  • 查找具有特定文本、属性或 cssproperty 的元素并 对其执行任何操作,例如断言或通过计算其大小单击其右侧。

  • 鼠标悬停在每个匹配的元素上(如果你想浏览标签 子菜单 ul li / ol li)

更多数据已填充,更多可以执行断言。