SwiftUI XCUIElement - How to grab XCUIElement on the screen?

382 views Asked by At

TAKE_A_LOOK_AT_SCREENSHOT_HERE

I'm facing an issue with the UI test written in SwiftUI. I need to grab an element on the screen which is implemented with following the code:

HStack {
    Button(action: {
       if value != 0 {
          value -= 1
       }
    }) {
       Image(systemName: "minus.circle")
    }
    Text(String(value))
       .accessibilityIdentifier("person_\(text.lowercased())_count")
    Button(action: {
       value += 1
    }) {
       Image(systemName: "plus.circle")
    }
 }

When I'm trying to get access to minus.circle or plus.circle the recorder prints me the following code e.g for minus:

app.windows.children(matching: .other)
    .element.children(matching: .other)
    .element.children(matching: .other)
    .element.children(matching: .other)
    .element.children(matching: .other)
    .element.children(matching: .other)
    .element.children(matching: .other)
    .element.children(matching: .other)
    .element.children(matching: .button)
    .matching(identifier: "Remove").element(boundBy: 0)

My question is:

How to reduce the amount of calling .children(matching: .other) or create another correct path to get access to these buttons?

I tried to use:

var minusCircleTeens: XCUIElement { 
    app.windows.children(matching:.other)
        .element.children(matching: .other)
        .element.children(matching: .other)
        .element.children(matching: .other)
        .element.children(matching: .other)
        .element.children(matching: .other)
        .element.children(matching: .other)
        .element.children(matching: .other)
        .element.children(matching: .button)
        .matching(identifier: "Remove").element(boundBy: 0)
}

func removeTeens() {      
     minusCircleTeens.tap() 
}

And it works properly but I would like to cut the long path to the element and do that in a better way. Any ideas?

2

There are 2 answers

0
Roman Zakharov On

As long as your identifiers are unique, you can go with something like

func removeTeens() {      
     app.buttons["Remove"].tap()
}
0
Arqu07 On

Try to run the following command during the debug: po XCUIApplication() This will print all UI elements that you can use. I believe you can tap on the button image like this: app.images["plus.circle"].tap(). Unless you have more buttons like this, then add and use the accessibility identifier.