Roman Zakharov
Roman Zakharov

Reputation: 2273

Is it possible to match UI elements by labels using regex in XCUIElementQuery?

I'm currently learning how to create UI Tests in XCode.

I use XCUIElementQuery to locate alert and close it

let dismissSavedPasswordButton = app.alerts["Select a Saved Password to Use With “My App”"].buttons["Not Now"]

But for older devices (e.g. running iOS 9), this code should look like this

let dismissSavedPasswordButton = app.alerts["Select a Saved Safari Password to Use With “My App”"].buttons["Not Now"]

Is it possible to rewrite this code to make it universal?

Upvotes: 1

Views: 2336

Answers (3)

Roman Zakharov
Roman Zakharov

Reputation: 2273

It is possible if you extend XCUIElementQuery class. I do something similar in my code:

extension XCUIElementQuery {

    func softMatching(substring: String) -> [XCUIElement] {

        return self.allElementsBoundByIndex.filter { $0.label.contains(substring) }
    }
}

After that, you can match elements like this:

 let dismissSavedPasswordButton = app.alerts.softMatching(substring: "Password").first!.buttons["Not Now"]

Upvotes: 3

alannichols
alannichols

Reputation: 1506

Unless you have more than one not now button on the screen you could just use

app.buttons["Not Now"]

You don't need to specify any more than that.

Upvotes: 0

Mladen
Mladen

Reputation: 2210

Not a regex, but should work:

app.alerts.element(boundBy: 0)

Since you should have only one alert on the screen, just query it by position.

Upvotes: 0

Related Questions