victorydub
victorydub

Reputation: 135

iOS UITesting - How can I access the search bar in a NavigationStack for UI Testing?

How can I access the search bar within NavigationStack for UI Testing?

Code:

var body: some View {
    NavigationStack {
        List {
            // some elements
        }
     }
     .searchable(text: $searchText)
     .accessibilityIdentifier("SearchField")
}

and for my UI tests,

override func setUpWithError() throws {
    continueAfterFailure = false

    app = XCUIApplication() // Initializes the XCTest app
    app.launch() // Launches the app

    let searchField = app.searchFields["SearchField"]
    XCTAssertTrue(searchField.exists, "Search field should exist")
}

My question is if it is possible to access the searchbar that is embedded within NavigationStack or if that just isn't supported at the moment. Ideally, I'd like to be able to verify that the search bar exists and then be able to add text to the search bar and select the "search" button in the tests. Thanks all

Upvotes: 1

Views: 35

Answers (1)

Kiryl Famin
Kiryl Famin

Reputation: 337

  1. You should use setUpWithError() for initialization only, not for test itself
  2. Try using firstMatch instead of accessibilityIdentifier
  3. Ensure existence with waitForExistence(timeout:) because he search bar might take some time to appear, so waiting for it ensures the test doesn’t fail prematurely

The final code will look like this:

override func setUpWithError() throws {
    continueAfterFailure = false
    app = XCUIApplication()
    app.launch()
}

func testSearchFieldExistsAndCanEnterText() {
    let searchField = app.searchFields.firstMatch
    
    XCTAssertTrue(searchField.waitForExistence(timeout: 5), "Search field should exist")
    
    searchField.tap()
    
    searchField.typeText("SwiftUI Testing")
    
    app.keyboards.buttons["Search"].tap()
}

Please, try it and let me know if it helps!

Upvotes: 1

Related Questions