Testing if an Element is Visible in Xcode UI Tests

Testing if an Element is Visible in Xcode UI Tests

11 April 2024 Stephan Petzl Leave a comment Tech-Help

When automating user interface testing with Xcode, developers often need to verify the visibility of UI elements. A common challenge is determining whether an element’s .hidden property is correctly set, which affects its visibility on the screen. This article provides guidance on how to test for an element’s visibility using Xcode UI testing frameworks.

Understanding the Existence and Hittability of UI Elements

In the context of UI testing in Xcode, two properties are crucial for understanding whether a UI element is visible to the user: .exists and .hittable. An element’s .exists property indicates whether the element is present in the app’s UI hierarchy, while the .hittable property determines if the element can be interacted with (e.g., tapped) by the user.

Testing Element Visibility

To test whether an element is visible, you can use the .hittable property, which has been improved in recent Xcode updates to check if the element is not just present but also correctly displayed and interactable on the screen. Here’s an example of how you can use it in your tests:

let trackInfoLabel = app.staticTexts["Track Info"]
XCTAssertEqual(trackInfoLabel.exists, true)
XCTAssertEqual(trackInfoLabel.hittable, true)

This code asserts that the “Track Info” label exists within the app’s UI and is hittable, meaning it should be visible and interactable. If the label were hidden, the .hittable property would return false, and the test would fail:

XCTAssertEqual(trackInfoLabel.exists, true)
XCTAssertEqual(trackInfoLabel.hittable, false)

Alternative Methods

If you require an alternative approach to determine visibility, consider checking the frame size of the element. An element with a width or height of zero is effectively hidden from view:

let isElementHidden = element.frame.size.width == 0 || element.frame.size.height == 0

Conclusion

Testing for an element’s visibility is a common task in UI testing. By using the .hittable and .exists properties, developers can ensure that UI elements are not only present in the app’s hierarchy but also properly displayed and interactable. Remember to always test both the true and false conditions to verify that your UI behaves as expected under different circumstances.

Like this article? there’s more where that came from!