SwiftUIaccessibilityIdentifier 不适用于 UI 测试

问题描述 投票:0回答:1

我正在尝试将 Xcode UI 测试与 SwiftUI macOS 应用程序一起使用。辅助功能标识符似乎不起作用。

例如,以下代码显示了 UI 测试、用于打印元素树的调试器命令以及应用程序的代码。元素树不显示代码中设置的辅助功能标识符。此外,整个

NSViewRepresentable
丢失了,但我将把它留到另一个问题。

请注意,元素树中都缺少

Button1
FirstView
AppKitView
VStack1
。 ID
MyWindow
确实进入了树中。

我们如何在 SwiftUI 视图上设置辅助功能 ID,以便我们可以在 UI 测试中引用它们?

(我使用的是 Xcode 13.4.1,macOS 12.4)

func testExample() throws {
    // UI tests must launch the application that they test.
    let app = XCUIApplication()
    app.launch()
    let window = app.windows.element(boundBy: 0)
    print("stop here.") // Set a break point here to look at stuff
}
(lldb) po print(window.debugDescription)
    [...]
Attributes: Window (Main), 0x7fd7f09087b0, {{270.0, 132.0}, {250.0, 278.0}}, identifier: 'MyWinID-AppWindow-1', title: 'Title', Keyboard Focused, Disabled
Element subtree:
 →Window (Main), 0x7fd7f09087b0, {{270.0, 132.0}, {250.0, 278.0}}, identifier: 'MyWinID-AppWindow-1', title: 'Title', Keyboard Focused, Disabled
    StaticText, 0x7fd7f09088e0, {{358.8, 160.0}, {72.5, 16.0}}, identifier: 'MyWindow', value: SwiftUI Text
    Button, 0x7fd7f0908a10, {{352.5, 186.0}, {85.5, 20.0}}, identifier: 'MyWindow', title: 'Test Button'
    Button, 0x7fd7f0908de0, {{277.0, 138.0}, {14.0, 16.0}}, identifier: '_XCUI:CloseWindow'
    Button, 0x7fd7f0908f10, {{317.0, 138.0}, {14.0, 16.0}}, identifier: '_XCUI:FullScreenWindow'
    Button, 0x7fd7f0909040, {{297.0, 138.0}, {14.0, 16.0}}, identifier: '_XCUI:MinimizeWindow'
    StaticText, 0x7fd7f0908b40, {{378.0, 137.0}, {33.0, 16.0}}, value: Title
struct ContentView: View {
    var body: some View {
        VStack {
            Text("SwiftUI Text").accessibilityIdentifier("FirstView")
            Button("Test Button") {
                print("clicked")
            }.accessibilityIdentifier("Button1")
            AppKitView().accessibilityIdentifier("AppKitView")
        }.accessibilityIdentifier("VStack1")
    }
}

struct AppKitView: NSViewRepresentable {
    typealias NSViewType = AppKitViewImpl
    func makeNSView(context: Context) -> AppKitViewImpl {
        let v = AppKitViewImpl()
        return v
    }
    func updateNSView(_ nsView: AppKitViewImpl, context: Context) {
        
    }
}

@main
struct DemoUITestsApp: App {
    var body: some Scene {
        WindowGroup("Title", id: "MyWinID") {
            ContentView()
                .frame(width: 250, height: 250)
                .accessibilityIdentifier("MyWindow")
        }
    }
}
macos swiftui accessibility xctest xcode-ui-testing
1个回答
0
投票

为了在 macOS 应用程序的 SwiftUI 预览中使用辅助功能标识符,您需要指定辅助功能环境。这可以通过将 .environment(.accessibilityEnabled, true) 添加到结构中来实现。

© www.soinside.com 2019 - 2024. All rights reserved.