UI testing a tab bar controller
Asked Answered
R

4

10

I have built a simple tab bar with 3 tabs.

enter image description here

I want to run a UI test to make sure that if the user clicks a tab bar item, the correct view controller shows. How would I go about doing that? Below is the code I would start with, just don't know how to write my assertion.

func testTabBarMyProfileButton() {
    let tabBarsQuery = XCUIApplication().tabBars
    tabBarsQuery.buttons["My Profile"].tap()
}

func testTabBarGraphsButton() {
    let tabBarsQuery = XCUIApplication().tabBars
    tabBarsQuery.buttons["Graphs"].tap()
}

func testTabBarAboutButton() {
    let tabBarsQuery = XCUIApplication().tabBars
    tabBarsQuery.buttons["About"].tap()
}
Rosenberg answered 25/10, 2016 at 2:9 Comment(0)
A
7

If you have different controls in each view controller shown on each tab bar, you can make assertions if they exist or not (what is expected). For example if the first tab bar has UILabel named "First name" you can assert if it exists by writing

Let theLabel = app.staticTexts["myValue"]
XCTAssert(theLabel.exists).to(beTrue)

And on the other screens do the same thing for the different controls.

Alcmene answered 25/10, 2016 at 2:51 Comment(0)
G
10

You can access the tabbar button by its position:

app.tabBars.buttons.element(boundBy: 2).tap()
Goldner answered 28/5, 2020 at 21:2 Comment(1)
This helped me. One additional info: the tabBars.buttons.element start from index 0. So the first tab bar item is 0, second one is 1 etc.Pisgah
A
7

If you have different controls in each view controller shown on each tab bar, you can make assertions if they exist or not (what is expected). For example if the first tab bar has UILabel named "First name" you can assert if it exists by writing

Let theLabel = app.staticTexts["myValue"]
XCTAssert(theLabel.exists).to(beTrue)

And on the other screens do the same thing for the different controls.

Alcmene answered 25/10, 2016 at 2:51 Comment(0)
A
4

If anyone finds this looking to UI test the contents of another app, I just found a solution..

The tab bar item is a lazy variable and needs to be touched before you can reference a tab bar button by value. Add this line:

tabBarItem.accessibilityIdentifier = "my-snazzy-identifier"

to the viewDidLoad method and you should be able to do this in your UI tests:

app.tabBars.buttons["Button Title"].tap()
Afterbirth answered 22/4, 2019 at 4:25 Comment(0)
N
1

You can test the title of the navigation bar.

XCTAssert(app.navigationBars["Graphs"].exists)

See my GitHub repo for a more detailed UI Testing example.

Ninetta answered 25/10, 2016 at 2:27 Comment(2)
I wasn't planning on using a navigation bar. Is there another way?Rosenberg
You will have to assert something unique in each screen. This can be anything from a button, text label, or UI control.Ninetta

© 2022 - 2024 — McMap. All rights reserved.