How to access a right item button on navigation bar in XCUITest?
Asked Answered
L

2

8

I am writing UITest cases for my iOS Swift app. In the app I have created a custom right item button on the navigation bar in this way:

let barButtonItem = UIBarButtonItem(customView: customView)
navigationItem.rightBarButtonItem = barButtonItem

Now I don't know how to access this custom right item button in XCUITest and really need some help. Thanks in advance.

Libbie answered 9/1, 2019 at 19:28 Comment(0)
T
14

You cannot access a UIBarButtonItem, because it is not a real UIElement (it is not a UIView subclass), but you probably want to access the UIButton inside your right bar button item anyway.

There are several ways how you could access the button, here are two ideas:

1. Query the first button in the navigation bar

let rightNavBarButton = XCUIApplication().navigationBars.children(matching: .button).firstMatch
XCTAssert(rightNavBarButton.exists)

That way you access the first UIButton inside a UINavigationBar.

This only works if there is only one button in your navigation bar. So it will break when you add another button.

2. Use an accessibility identifier

You can define a accessibility identifier for the button inside your right bar button item and use that to access it during the test:

In your app:

let barButtonItem = UIBarButtonItem(customView: customView)
barButtonItem.accessibilityIdentifier = "navbarRightItem"
navigationItem.rightBarButtonItem = barButtonItem

In your test:

let rightNavBarButton = XCUIApplication().navigationBars.buttons["navbarRightItem"]
XCTAssert(rightNavBarButton.exists)

Just make sure you are using accessibilityIdentifier and not accessibilityLabel. Because accessibilityLabel will be read by VoiceOver for handicapped users and should contain useful text.

Tappet answered 15/1, 2019 at 15:35 Comment(4)
It still doesn't work. XCTAssert(rightNavBarButton.exists) failed. But anyway, thanks a lot!Libbie
Is your customView a UIButton?Tappet
Actually the customView was a UIView, which contains an UIImageView to host an image. I changed the customView to a UIButton and then it worked by app.navigationBars["myNavigationBarAccessibilityIdentifier"].buttons.element(boundBy: 0).tap(). Thanks!Libbie
The reason I was not using UIButton for the rightBarButtonItem's customView is that UIButton's setImage method doesn't work well with a custom image. But that is another topic though.Libbie
S
0

You have to assign an accessibilityIdentifier to the button

barButtonItem.accessibilityIdentifier = “barButtonItemID”

If didn’t work set IsAccessibilityElement to YES/true

Sundown answered 24/6, 2020 at 15:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.