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
setUpWithError()
for initialization only, not for test itselffirstMatch
instead of accessibilityIdentifier
waitForExistence(timeout:)
because he search bar might take some time to appear, so waiting for it ensures the test doesn’t fail prematurelyThe 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!