ios - UITesting -> NavigationItem 的 titleView 中的 UISearchBar 返回 XCUIElement.Type other

标签 ios swift xcode-ui-testing ui-testing

我将 UIViewController 的 navigationItem 的 titleView 设置为 UISearchBar。这在应用程序中运行良好,但现在我正在尝试添加一些 UITesting,当我通过 XCUIElementQuery 搜索元素时,它返回 XCUIElement.Type 作为 .other 而不是我所期望的 .searchField。随后,当我尝试使用 XCUIApplication().typeText("abcd") 在字段中输入文本时,我的测试崩溃了。这是一些示例代码:

在 View Controller 中:

override func viewDidLoad() {
        let searchBar = UISearchBar()
        searchBar.isAccessibilityElement = true
        searchBar.accessibilityIdentifier = "search-bar" 

        searchBar.delegate = self.searchViewController
        self.navigationItem.titleView = searchBar
}

在 UITest 中:

func testEnterTextInSearchBar() {        
    let app = XCUIApplication()
    let searchBarElement = app.descendants(matching: .any).matching(identifier: "search-bar").firstMatch
    searchBarElement.tap()
    app.typeText("test")
}

崩溃!!!因为它认为类型是 .other 而不是 .searchField

错误是:“元素和任何后代都没有键盘焦点。元素: 属性:其他,0x608000192f10,特征:8589934592,标识符:'search-bar'”

只要启用了软件键盘,也可以使用 app.keys["x"].tap() 正常工作。

最佳答案

第 1 步:禁用硬件键盘。你可以在

Hardware --> Keyboard --> Connect Hardware keyboard [Disable this option]

第 2 步:

 func testEnterTextInSearchBar() {        
 let app = XCUIApplication()

 // use one of below two  code
 let searchBarElement = app.otherElements["search-bar"].tap().firstMatch
 //let searchBarElement = app.searchFields["search-bar"].tap().firstMatch


 searchBarElement.tap()
 searchBarElement.typeText("test")

请告诉我结果。

关于ios - UITesting -> NavigationItem 的 titleView 中的 UISearchBar 返回 XCUIElement.Type other,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47543220/

相关文章:

iphone - 如何以用户位置为中心设置 map 矩形?

ios - 以编程方式切换 UISwitch,阻止 IBAction 功能

swift - 覆盖 Swift 3 中的属性

ios - 访问另一个 View Controller 的函数时意外发现 nil

ios - WKInterfaceTable 和 setNumberOfRows 崩溃 "unexpectedly found nil while unwrapping an Optional value"

cocoa - 使用多个 XCTestCase 类进行 UITesting

ios - 添加自定义按钮后,将后退按钮添加回 navigationController

ios - 在 UITest 中无法找到/单击 Apple Pay View 上的任何元素

ios - XCTest 无法访问屏幕上的错误消息标签

ios - 如何理解“当使用带有__weak限定词的变量时,该对象总是在autoreleasepool中注册”