Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS XCUITests access element by accessibility

Tags:

ios

swift

xctest

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

like image 914
Godfather Avatar asked Jan 03 '17 11:01

Godfather


4 Answers

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.

like image 184
Oletha Avatar answered Sep 28 '22 11:09

Oletha


IMPORTANT NOTE: If a superview is set to accessible, XCUITest might not be able to access its subviews.

You can access the element by setting its accessibility via the storyboard or programmatically as discussed above. You can click the record button when your cursor is in a function which starts with the prefix "test" in order to record how XCUITest sees an element. Sometimes it takes a couple cleans (command shift k) and a couple minutes for the record button to be available. You can also step down your tree from storyboard and use XCUITest functions such as element(boundBy: Int), children(matching: .textField), you can chain them as well: XCUIApplication().tables.cells.containing(.button, identifier: "id"). After that is the easy part, use .exists which returns a boolean.

enter image description here

like image 38
ScottyBlades Avatar answered Sep 28 '22 12:09

ScottyBlades


add | "accessibilityIdentifier" String test | in the User Defined Runtime Attributes on the navigation bar, instead of in the accessibility label

like image 9
Stefan Avatar answered Sep 28 '22 13:09

Stefan


I got the same issue because the keyboard covered the button so:

app.buttons["Done"].tap()

solved the issue.

like image 1
William Hu Avatar answered Sep 28 '22 13:09

William Hu