Xcode UI Testing can't find elements

Viewed 544

I'm trying UITesting on Xcode. App show Alert when tap button, then open Modal when tap "open" button on alert. UITesting can find that element, but can't find element after show modal. If remove alert from app, can find element after show modal. Why can't find element in that app? What I should do? Please help me

struct ContentView: View {
    @State var showSheet = false
    @State var showAlert = false

    var body: some View {
        HStack{
            Button(action: {
                showAlert = true
            }, label: {
                Text("button")
            })
            .accessibility(identifier: "button")
        }
        .sheet(isPresented: $showSheet, content: {
            Modal(showModal: $showSheet)
        })
        .alert(isPresented: $showAlert) { () -> Alert in
            Alert(title: Text("title"), message: Text("message"), primaryButton: .default(Text("open"), action: {
                showSheet = true
            }), secondaryButton: .cancel())
        }
    }
}

struct Modal: View{
    @Binding var showModal: Bool

    init(showModal: Binding<Bool>){
        self._showModal = showModal
    }

    var body: some View {
        return ZStack(alignment: .top) {
            Button {
                showModal.toggle()
            } label: {
                Text("back")
            }
            .accessibility(identifier: "button2")
        }
        .accessibility(identifier: "modal")
    }
}
    func testExample() throws {
        let app = XCUIApplication()
        app.launch()

        app.buttons["button"].tap()
        sleep(1)

        app.buttons["open"].tap()
        sleep(1)

        let result = app.buttons["button2"]
        XCTAssert(result.exists)
    }
1 Answers

It works with use of label, like (tested with Xcode 13beta / iOS 15)

    let result = app.buttons["back"]
    XCTAssert(result.exists)

also it seems second identifier overrides needed, so you can remove it

    return ZStack(alignment: .top) {
        Button {
            showModal.toggle()
        } label: {
            Text("back")
        }
        .accessibility(identifier: "button2")
    }
//  .accessibility(identifier: "modal")     // << PASSED [!]
Related