Xcode UI test cannot tap menu button in form

Apparently UI tests are unable to tap menu buttons but can tap regular buttons inside forms. Earlier today I was able to see in the Simulator that the UI test tries to tap the button by tapping the center of the containing form row, which works for regular buttons, but not for menu buttons. In fact, when trying in the SwiftUI preview in Xcode it seems that menu buttons have to be tapped exactly on top of them, while regular buttons can be tapped anywhere in the form row. (Now I’m not able to see touches performed by the UI test anymore in the Simulator for an unknown reason, even though I have “Show single touches” enabled in the Simulator settings.)

How can I open a menu button in a UI test?

The UI code:

struct ContentView: View {
    @State private var label1 = "Menu 1"
    @State private var label2 = "Menu 2"

    var body: some View {
        NavigationStack {
            Form {
                LabeledContent("Menu 1") {
                    Button(label1) {
                        label1 = "Menu 1 tapped"
                    }
                    .accessibilityIdentifier("menu1")
                }
                LabeledContent("Menu 2") {
                    Menu(label2) {
                        Button("Button") {
                            
                        }
                        .accessibilityIdentifier("button")
                    }
                    .accessibilityIdentifier("menu2")
                }
            }
        }
    }
}

#Preview {
    ContentView()
}

And the test:

final class problemUITests: XCTestCase {

    func testExample() throws {
        // UI tests must launch the application that they test.
        let app = XCUIApplication()
        app.launch()
        
        app.collectionViews.element(boundBy: 0).buttons["menu1"].tap()
        app.collectionViews.element(boundBy: 0).buttons["menu2"].tap()
        app.collectionViews.element(boundBy: 0).buttons["button"].tap()
    }
}

Is "menu2" a button element? It might be a menuButton

You can see what type it is by printing app.debugDescription and searching for "menu2"

You can see what type it is by printing app.debugDescription and searching for "menu2"

Sorry for my late reply, once again I wasn't notified of a new post even though I'm subscribed to this topic.

Here's the output I get when running app.debugDescription. Both menu1 and menu2 seem to be buttons.

Xcode UI test cannot tap menu button in form
 
 
Q