UI XCTest,视图中存在的元素

UI XCTest, elements which exist in view

我是 UI 测试写作的新手。

我想知道是否可以知道视图中的元素 are/exists。我想知道有多少,怎么称呼。

我试过类似这样的方法来遍历所有元素,但它不起作用。

for element in app.accessibilityElements! {
        print(element)
    }

您正在寻找 XCUIElement 的 debugDescription 方法,在您的情况下获取当前可见的整个层次结构 window:

app.debugDescription

引用 header 条评论:

Provides debugging information about the element. The data in the string will vary based on the time at which it is captured, but it may include any of the following as well as additional data:

   • Values for the elements attributes.
   • The entire tree of descendants rooted at the element.
   • The element's query.

This data should be used for debugging only - depending on any of the data as part of a test is unsupported.

您始终可以在测试用例中设置一个断点,然后对控制台进行一些打印调用。

po app.accessibilityElements po app.accessibilityElements.elementBoundByIndex(0) po app.buttons["Icon Menu Light"] etc.

并查看输出视图层次结构中返回的内容以供参考,或者只需简单调用 po app 即可打印层次结构。

一旦你知道一个特定的视图存在.. app.buttons["Icon Menu Light"].exists.. 然后你可以尝试使用这样的东西来确认 button/element 在当前视图中可见,方法是将它传递给辅助函数喜欢:

func isElementInView(element: XCUIElement) -> Bool {
   let window = XCUIApplication().windows.elementBoundByIndex(0)
   return CGRectContainsRect(window.frame, element.frame) }

这将告诉您该元素是否在屏幕上可见,因为 element.exist 调用将 return 为真,即使该元素不在屏幕上并且没有显示给用户(即如果某些东西隐藏在屏幕之外然后过渡到框架中)