2

Is it somehow possible to simulate a tap when testing (ex. snapshot tests) a tap or any other gesture in SwiftUI?

For UIKit we can do something like:

button.sendActions(for: .touchUpInside)

Is there any SwiftUI equivalent?

Fengson
  • 4,751
  • 8
  • 37
  • 62
  • Does this answer your question https://stackoverflow.com/a/64953369/12299030? – Asperi Mar 31 '22 at 07:25
  • https://github.com/nalexn/ViewInspector i'm using this lib for my uitests, or you can try Appium. Behind the SwiftUI view is also UIView, basically they are similar. – Quang Hà Mar 31 '22 at 07:31
  • One more useful answer: https://stackoverflow.com/questions/66433076/how-to-click-a-button-programmatically-in-swiftui – Andrew Mar 31 '22 at 08:39

1 Answers1

0

While it's not directly possible to "Simulate" in the fashion you're attempting to simulate, it is perfectly possible to simulate the actions behind the buttons. This is assuming that you're using an MVVM architecture. The reason for this is that if you "Simulate" via the backing methods that support the buttons, via the view model, then you will still get the same result. In addition to this, SwiftUI will update and recalculate the views upon any state change, meaning it doesn't matter if the button changes a state or if a method changes the state. You can then extend that functionality to the init() function of the view struct, and viola, you'll be simulating actions.

View Model Example

class VMExample: ObservableObject {
    @Published var shouldNavigate = false

    func simulateNavigate() { 
        shouldNavigate.toggle 
    }
}

View Example

struct MyView: View {
    @ObservedObject var vm = VMExample()

    var body: some View {
        NavigationLink(
                       "Navigate",
                       destination: Text("New View"),
                       isActive: $vm.shouldNavigate)
            .onAppear {
                //If Debug
                vm.simulateNavigate()
            }
    }
}

Simulating multiple actions

To do it with multiple actions, you could potentially create some function func beginSimulation() that begins running through all the actions you want to test. You might change some text, navigate to a view, etc...

TL;DR

Simulate the actions behind the buttons, not the buttons interactions themselves. The result will be the same due to View Binding.

xTwisteDx
  • 2,152
  • 1
  • 9
  • 25