Skip to content

Instantly share code, notes, and snippets.

@yannxou
Created December 11, 2024 08:51
Show Gist options
  • Save yannxou/135daf5eb3f14a6f6bd3fc9db4a7068a to your computer and use it in GitHub Desktop.
Save yannxou/135daf5eb3f14a6f6bd3fc9db4a7068a to your computer and use it in GitHub Desktop.
XCUIElementQuery Matching Extension
// Source: https://medium.com/@anthony.prokuda/how-to-locate-and-wait-for-an-element-in-xcuitest-a-powerful-approach-105b81628986
extension NSPredicate {
static func keyPath<T, U>(
_ keyPath: KeyPath<T, U>,
is type: NSComparisonPredicate.Operator = .equalTo,
value: U,
modifier: NSComparisonPredicate.Modifier = .direct,
options: NSComparisonPredicate.Options = []
) -> NSPredicate {
return NSComparisonPredicate(
leftExpression: NSExpression(forKeyPath: keyPath),
rightExpression: NSExpression(forConstantValue: value),
modifier: modifier,
type: type,
options: options
)
}
}
extension XCUIElementQuery {
func matching<U>(
attribute keyPath: KeyPath<XCUIElementAttributes, U>,
is comparisonOperator: NSComparisonPredicate.Operator,
value: U,
options: NSComparisonPredicate.Options = []
) -> XCUIElementQuery {
let predicate = NSPredicate.keyPath(
keyPath,
is: comparisonOperator,
value: value,
options: options
)
return matching(predicate)
}
}
// Sample usage:
let label = app.staticTexts.matching(
attribute: \.label,
is: .contains,
value: "Message",
options: .caseInsensitive
).firstMatch
// with regex:
let label = app.staticTexts.matching(
attribute: \.label,
is: .matches,
value: "[0-9]+ Message"
).firstMatch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment