How can I test for the existence of a UIView using XCUIElementsQuery?
Asked Answered
U

2

5

It is difficult to find proper documentation for the UI Testing Framework from Apple. I've seen many examples where it is possible to find buttons and labels with specific names, but how can I look for generic UIViews?

For example, suppose I set a view with accessibilityLabel == "Some View", how can I find a view with that name during the test execution?

I tried (unsuccessfully) the following code:

XCUIElement *pvc = [[app childrenMatchingType:XCUIElementTypeAny] elementMatchingPredicate:[NSPredicate predicateWithFormat:@"accessibilityLabel == 'Places View'"]];

NSPredicate *exists = [NSPredicate predicateWithFormat:@"exists == true"];
[self expectationForPredicate:exists evaluatedWithObject:pvc handler:nil];
[self waitForExpectationsWithTimeout:10 handler:nil];

NSLog(@"%@", [[app childrenMatchingType:XCUIElementTypeAny] elementMatchingPredicate:[NSPredicate predicateWithFormat:@"accessibilityLabel == 'Places View Controller'"]]);
Uttica answered 14/12, 2015 at 18:45 Comment(0)
P
7

The problem I see with the code you have above is that you're specifically trying to find a view in the children of the app, instead of the descendants of the app. Children are strictly subviews of a view, and the search won't look at sub-sub-views, etc. Other than that, it looks fine.

Try:

XCUIElement *pvc = [[app descendantsMatchingType:XCUIElementTypeAny] elementMatchingPredicate:[NSPredicate predicateWithFormat:@"accessibilityLabel == 'Places View'"]];

Also, the default for UIView is to not participate in accessibility at all, so in addition to setting the label (and incidentally the code snippet in your question about setting a label is doing comparison instead of assignment) you should also make sure you enable accessibility:

view.isAccessibilityElement = YES
view.accessibilityLabel = @"AccessibilityLabel"
Prajna answered 14/12, 2015 at 18:51 Comment(2)
Oh I see my mistake with looking for the children. Unfortunately searching for descendants didn't work either... I tried setting a large timeout but Xcode didn't find a view with that accessibilityLabel.Uttica
If you use the accessibility inspector, can you select the view you're trying to find? You need to make sure accessibility is enabled in addition to setting a label. By default I believe that UIView is not enabled for accessibility.Prajna
S
2

The query from the other answer works, but I find that you can also find views simply with:

app.otherElements["MenuViewController.menuView"].swipeLeft()

Where in my case MenuViewController.menuView is a UIView with an accessibilityIdentifier set.

Skilling answered 23/6, 2016 at 20:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.