44

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
  • Setting the accessibility identifier is the most robust way as it will give you independence from the label text. – Lance Kind Sep 30 '18 at 19:18

4 Answers4

62

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

app.navigationBars.buttons.element(boundBy: 0).tap()
Luke
  • 4,908
  • 1
  • 37
  • 59
  • 8
    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()`. – Aaron Sofaer Jul 28 '16 at 20:09
  • 1
    what if there is no back button and another button will be tapped? doesn't work well... need to assign identifier – Injectios Mar 21 '17 at 12:57
15

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

enter image description here

d4Rk
  • 6,622
  • 5
  • 46
  • 60
11

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

app.navigationBars.buttons.element(boundBy: 0).tap()
dustinrwh
  • 888
  • 1
  • 14
  • 16
0

Objective-C:

[[app.navigationBars.buttons elementBoundByIndex:0] tap];
shim
  • 9,289
  • 12
  • 69
  • 108
hanno
  • 6,401
  • 8
  • 48
  • 80
  • 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 accessibilityIdentifier – Eduard Apr 19 '23 at 07:24