我试图在我的Xcode 11项目上运行UI测试(以在整个快速通道上生成快照),但是我面临着一个相当奇怪的情况。
运行测试时,显示主页后该应用程序立即崩溃,并显示错误:
Fatal error: No ObservableObject of type TabCommands found. A View.environmentObject(_:) for TabCommands may be missing as an ancestor of this view.: file SwiftUI, line 0
但是正常运行应用程序时,我没有这样的错误。
这是应用程序的层次结构:
let contentView = ContentView()
.environmentObject(UserManager())
.environmentObject(TabCommands())
.environmentObject(IAPStore())
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
var body: some View {
UIKitTabView([
UIKitTabView.Tab(view: NavigationView {
HomeContentView()
Spacer()
}, title: "menu_home".localized(), image: "house"),
UIKitTabView.Tab(view: NavigationView {
SearchView()
Spacer()
}, title: "menu_home".localized(), image: "magnifyingglass"),
UIKitTabView.Tab(view: NavigationView {
UserTabRootLoading()
Spacer()
}, title: "menu_home".localized(), image: "person.crop.circle"),
])
.edgesIgnoringSafeArea(.bottom)
.edgesIgnoringSafeArea(.top)
}
崩溃发生在SearchView主体内部,在导航链接中,将EnvironmentVariable对象用于isActive
状态(以便稍后在不传递值的情况下弹出3个Views)。
struct SearchView: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
@EnvironmentObject var tabCommands: TabCommands
@EnvironmentObject var userManager: UserManager
var body: some View {
ZStack {
Color.black.edgesIgnoringSafeArea(.all)
NavigationLink(destination: PremiumView()
.navigationBarTitle("")
.navigationBarHidden(true),
isActive: self.$tabCommands.isStartPremiumViewActive) {
EmptyView()
}.isDetailLink(false)
}
}
(我删除了其余代码)
TabCommand 是具有6行@Published var myVar = false
的ObservableObject
同样,当我在模拟器或设备上运行该应用程序时,该应用程序按预期运行,只有在启动UI测试时才会出现问题。
当我尝试仅用
进行简单测试时let app = XCUIApplication()
app.launch()
测试成功。添加第一行app.staticTexts["MainButton"].tap()
在“场景委托”中是否需要进行一些配置以启用“环境对象”或其他功能?
答案 0 :(得分:0)
在SearchView后面添加.environmentObject(TabCommands())...以及在那里使用的所有其他Environmentobjects ...不仅限于ContentView。
像这样:
UIKitTabView.Tab(view: NavigationView {
SearchView().environmentObject(TabCommands())
Spacer()
}, title: "menu_home".localized(), image: "magnifyingglass"),