简体   繁体   English

SwiftUI - 测试 - 模拟点击手势?

[英]SwiftUI - testing - simulate tap gesture?

Is it somehow possible to simulate a tap when testing (ex. snapshot tests) a tap or any other gesture in SwiftUI?在 SwiftUI 中测试(例如快照测试)点击或任何其他手势时,是否有可能模拟点击?

For UIKit we can do something like:对于 UIKit,我们可以这样做:

button.sendActions(for: .touchUpInside)

Is there any SwiftUI equivalent?是否有 SwiftUI 等价物?

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.这是假设您使用的是 MVVM 架构。 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.这样做的原因是,如果您通过支持按钮的支持方法“模拟”,通过视图 model,那么您仍然会得到相同的结果。 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.除此之外,SwiftUI 将在任何 state 更改时更新并重新计算视图,这意味着按钮更改 state 或方法更改 state 都没有关系。然后您可以将该功能扩展到init() function视图结构和中提琴,您将模拟操作。

View Model Example查看 Model 示例

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.要使用多个操作来执行此操作,您可能会创建一些 function func beginSimulation()开始运行您要测试的所有操作。 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.由于视图绑定,结果将是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM