How to access back bar button item in universal way under UITests in Xcode?
Asked Answered
P

4

46

The problem is when I try to access back bar button item because it is presented with:

  • Restaurants title,
  • Back title
  • without title

Like it is on the screens:

enter image description here

enter image description here

enter image description here

Currently I access it like this:

let backButton = XCUIApplication().buttons["Restaurants"]

but it won't work for other cases. It is not universal way. May I somehow set it accessibilityIdentifier or something else?

Posterity answered 26/7, 2016 at 16:27 Comment(1)
Setting the accessibility identifier is the most robust way as it will give you independence from the label text.Avera
K
64

Generally the back button tends to be the first button element in the navigation bar

app.navigationBars.buttons.element(boundBy: 0).tap()
Keirakeiser answered 26/7, 2016 at 16:32 Comment(2)
You can also add an accessibilityIdentifier to the back button when you're creating it (e.g., backButton.accessibilityIdentifier = "back") and then you just do app.buttons["back"].tap().Imide
what if there is no back button and another button will be tapped? doesn't work well... need to assign identifierPrudence
R
15

Based on Aaron Sofaers comment, you can also set the accessibilityIdentifier directly in Interface Builder.

enter image description here

Rachealrachel answered 17/8, 2017 at 13:2 Comment(7)
Can you do this for the backBarButtonItem though?Ardath
You should be able to do so, when you create it in a storyboard/xib.Rachealrachel
Ah, but not programmatically?Ardath
I don't think, you can access a programmatically created button in the Interface Builder?!Rachealrachel
I mean, if I create the button programmatically and set the accessibilityIdentifier programmatically. I tried that and it didn't work.Ardath
What did you do exactly? It should work, as Aaron Sofaer described it in his comment above.Rachealrachel
This doesn't seem to work aqt least as of iOS 11 / Xcode 9. Asserting button.exists fails.Rummer
T
10

Here's how you can do it in Swift 3:

app.navigationBars.buttons.element(boundBy: 0).tap()
Trapezium answered 18/4, 2017 at 13:49 Comment(1)
What is the difference between this answer and the accepted one which was posted almost a year earlier?Cherlycherlyn
E
0

Objective-C:

[[app.navigationBars.buttons elementBoundByIndex:0] tap];
Edmondson answered 5/7, 2020 at 23:52 Comment(1)
Not the best solution because order of the buttons can be changed, and test case will fail. It's better to access the element using accessibilityIdentifierDodecasyllable

© 2022 - 2024 — McMap. All rights reserved.