iOS XCUITests access element by accessibility

Godfather picture Godfather · Jan 3, 2017 · Viewed 23.5k times · Source

How do I assert a button exists by his accessibilityLabel or identifier?

func testExitsButton() {
    XCTAssertTrue(app.windows.containing(.button, identifier: "Button Text").element.exists)
    XCTAssertTrue(app.buttons["Button Text"].exists)
    XCTAssertTrue(app.buttons["test"].exists) <- I want this, instead of accessing the text property I want by specific id, maybe the text property override the accessibilityLabel?
}

enter image description here

Answer

Oletha picture Oletha · Jan 4, 2017

Set an accessibility identifier in your application code, and then search for the button using that identifier in your tests.

// app code
let button: UIButton!
button.accessibilityIdentifier = "myButton"

// UI test code
func testMyButtonIsDisplayed() {
    let app = XCUIApplication()
    let button = app.buttons["myButton"]
    XCTAssertTrue(button.exists)
}

The accessibility identifier is set independently of text on the button, and is also independent of the accessibility label. It's not best practice to put identifiers for UI elements as the accessibility label, since the accessibility label is read to VoiceOver users to explain the element to them.