XCTest() 获取 XCUIElement 的父级

sas*_*iko 4 automation automated-tests xctest swift

这是我po print(XCUIApplication().debugDescription)在终端窗口中输入时尝试打印应用程序元素结构时的示例

tables, (address code like 0x00006b), traits: (some random number)
    cells, (address code), traits: (random number)
       others, (address code), traits: (random number), label: "Other Value"
       buttons, (address code), traits: (random number), identifier: "primaryButton", label: "Press ME"
Run Code Online (Sandbox Code Playgroud)

所以,基本上,如果我想访问others价值,我只需要通过它的标签简单地访问:

let cellsValue = XCUIApplication().tables.cells.otherElements.staticTexts["Other Value"];

但是,问题是staticTexts可以超时更改,所以我的解决方案是我可以访问具有特定标识符的元素,例如:

let btnPrimary = XCUIApplication().tables.buttons["primaryBtn"];
Run Code Online (Sandbox Code Playgroud)

并调用它的父级(在这种情况下为单元格元素),例如:

let tableParent = btnPrimary.parent() 
Run Code Online (Sandbox Code Playgroud)

这样我就可以使用以下方法轻松访问该元素:

let otherElement = tableParent.otherElements.firstMatch.label
Run Code Online (Sandbox Code Playgroud)

但是该parent()函数不存在,那么我如何才能访问元素的父元素?

sas*_*iko 6

我找到了这个问题的解决方案,我把它贴在这里,以防有人和我一样有同样的问题。因此,您不必根据具有唯一标识符的子项来查找父项,您只需要根据 XCTest() 给出的内容查找具有唯一标识符的元素即可。所以基本上,你必须这样做:

let parent = XCUIApplication().tables.cell.containing(.button, "primaryButton")
Run Code Online (Sandbox Code Playgroud)

并通过以下方式访问他们的孩子:

let otherValue = parent.otherElements.firstMatch()
Run Code Online (Sandbox Code Playgroud)

这将返回第一个元素的类型,other如果要访问元素索引,请调用element(boundBy: )方法!

  • 如果孩子没有唯一的 id,那你就不走运了 (2认同)