Programing

UI 테스트 실패-요소 나 하위 요소 모두 secureTextField에 키보드 포커스가 없습니다.

lottogame 2020. 8. 14. 08:11
반응형

UI 테스트 실패-요소 나 하위 요소 모두 secureTextField에 키보드 포커스가 없습니다.


이것은 내 경우입니다.

let passwordSecureTextField = app.secureTextFields["password"]
passwordSecureTextField.tap()
passwordSecureTextField.typeText("wrong_password") //here is an error

UI 테스트 실패-요소 나 하위 요소 모두 키보드 포커스가 없습니다. 요소:

뭐가 잘못 되었 니? 이것은 정상적으로 작동 textFields하지만 문제는 secureTextFields. 해결 방법이 있습니까?


이 문제로 인해 고통 스러웠지만 적절한 해결책을 찾았습니다. 시뮬레이터에서 '하드웨어-> 키보드-> 하드웨어 키보드 연결'이 꺼져 있는지 확인합니다.


최근에 우리는 수용된 답변으로부터 솔루션을 지속적으로 만드는 해킹을 발견했습니다. 시뮬레이터 설정을 비활성화하려면 명령 줄에서 '하드웨어-> 키보드-> 하드웨어 키보드 연결'을 작성해야합니다.

defaults write com.apple.iphonesimulator ConnectHardwareKeyboard 0

실행중인 시뮬레이터에는 영향을주지 않습니다. 시뮬레이터를 다시 시작하거나 해당 설정이 적용되도록하려면 새로운 시뮬레이터를 시작해야합니다.


저에게 딱 맞는 작은 확장 프로그램 (Swift)을 작성했습니다. 다음은 코드입니다.

extension XCTestCase {

    func tapElementAndWaitForKeyboardToAppear(element: XCUIElement) {
        let keyboard = XCUIApplication().keyboards.element
        while (true) {
            element.tap()
            if keyboard.exists {
                break;
            }
            NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceNow: 0.5))
        }
    }
}

주요 아이디어는 키보드가 표시되기 전에 요소 (텍스트 필드)를 계속 탭하는 것입니다.


Stanislav는 올바른 아이디어를 가지고 있습니다.

팀 환경에서는 자동으로 작동하는 무언가가 필요합니다. 여기 내 블로그 에서 수정 사항 을 찾았습니다.

기본적으로 붙여 넣기 만하면됩니다.

UIPasteboard.generalPasteboard().string = "Their password"
let passwordSecureTextField = app.secureTextFields["password"]
passwordSecureTextField.pressForDuration(1.1)
app.menuItems["Paste"].tap()

이 오류의 또 다른 원인은 접근성 요소 ( view.isAccessibilityElement = true) 로 설정된 텍스트를 입력하려는 텍스트 필드의 상위 뷰가있는 경우 입니다. 이 경우 XCTest는 텍스트를 입력하기 위해 하위 뷰에서 핸들을 가져올 수 없으며 오류를 반환합니다.

UI 테스트 실패-요소 나 하위 요소 모두 키보드 포커스가 없습니다.

포커스가있는 요소가 없다는 것이 아닙니다 (UITextField에서 키보드가 위로 올라가고 커서가 깜박이는 것을 볼 수 있기 때문에) . 도달 할 수있는 요소 가 포커스가 없다는 입니다. UISearchBar에 텍스트를 입력하려고 할 때이 문제가 발생했습니다. 검색 창 자체는 텍스트 필드가 아니므로 접근성 요소로 설정하면 기본 UITextField에 대한 액세스가 차단됩니다. 이 문제를 해결하기 위해 searchBar.accessibilityIdentifier = "My Identifier"는에 설정되어 UISearchBar있지만은 isAccessibilityElement로 설정되지 않았습니다 true. 그 후 다음 형식의 코드를 테스트하십시오.

app.otherElements["My Identifier"].tap()
app.otherElements["My Identifier"].typeText("sample text")

공장


앱을 실행하고 다음과 같은 텍스트 필드에 데이터를 입력하는 사이에 절전 모드를 사용하십시오.

sleep(2)

제 경우에는 매번이 오류가 계속 발생 했으며이 솔루션만이 도움이되었습니다.


도움이 될 수 있습니다. 오류 앞에 "탭"동작을 추가합니다. 그게 다야 :)

[app.textFields[@"theTitle"] tap];
[app.textFields[@"theTitle"] typeText:@"kk"];

func pasteTextFieldText(app:XCUIApplication, element:XCUIElement, value:String, clearText:Bool) {
    // Get the password into the pasteboard buffer
    UIPasteboard.generalPasteboard().string = value

    // Bring up the popup menu on the password field
    element.tap()

    if clearText {
        element.buttons["Clear text"].tap()
    }

    element.doubleTap()

    // Tap the Paste button to input the password
    app.menuItems["Paste"].tap()
}

It occurred with me for many times. You have to disable Keyboard Hardware and Same Layout as OSX in your Simulator

Hardware/Keyboard (disable all)

After that keyboard software won't dismiss and your tests can type text

Disable Hardware


Record case however you want, keyboard or without keyboard attached. But do the following before playing test.

This following option (connect hardware keyboard) should be unchecked while playing test.

enter image description here


[Reposting Bartłomiej Semańczyk's comment as an answer because it solved the problem for me]

I needed to do Simulator > Reset Contents and Settings in the simulator menu bar to make this start working for me.


Your first line is just a query definition, which doesn't mean that passwordSecureTextField would actually exist.

Your second line will dynamically execute the query and try to (re)bind the query to UI element. You should put a breakpoint on it and verify that one and only one element is found. Or just use an assert:

XCTAssertFalse(passwordSecureTextField.exists);

Otherwise it looks ok, tap should force keyboard visible and then typeText should just work. Error log should tell you more info.


Don't messed up, There problem caught the reason is you are recorded your testing time your app will connection hardware keyboard while your automatic testing time simulator takes only software keyboard. so for how to fix this issues. Just use software keyboard on your recording time. you can see the magic.


The problem for me was the same as for Ted. Actually if password field gets tapped after login field and hardware KB is on, software keyboard will dismiss itself on second field tap, and it's not specific to UI tests.

After some time messing around with AppleScript, here's what I came up with(improvements are welcome):

tell application "Simulator" activate tell application "System Events" try tell process "Simulator" tell menu bar 1 tell menu bar item "Hardware" tell menu "Hardware" tell menu item "Keyboard" tell menu "Keyboard" set menuItem to menu item "Connect Hardware Keyboard" tell menu item "Connect Hardware Keyboard" set checkboxStatus to value of attribute "AXMenuItemMarkChar" of menuItem if checkboxStatus is equal to "✓" then click end if end tell end tell end tell end tell end tell end tell end tell on error tell application "System Preferences" activate set securityPane to pane id "com.apple.preference.security" tell securityPane to reveal anchor "Privacy_Accessibility" display dialog "Xcode needs Universal access to disable hardware keyboard during tests(otherwise tests may fail because of focus issues)" end tell end try end tell end tell

Create a script file with code above and add it to necessary targets(probably UI tests target only, you may want to add similar script to your development targets to re-enable HW keyboard during development). You should add Run Script phase in build phases and use it like this: osascript Path/To/Script/script_name.applescript


We encountered the same error when setting the accessibilityIdentifier value for a custom view (UIStackView subclass) containing UIControl subviews. In that case XCTest was unable to get the keyboard focus for the descendent elements.

Our solution was simply to remove the accessibilityIdentifier from our parent view and set the accessibilityIdentifier for the subviews through dedicated properties.


Sometime text fields are not implemented as text fields, or they're wrapped into another UI element and not easily accessible. Here's a work around:

//XCUIApplication().scrollViews.otherElements.staticTexts["Email"] the locator for the element
RegistrationScreenStep1of2.emailTextField.tap()
let keys = app.keys
 keys["p"].tap() //type the keys that you need
 
 //If you stored your data somewhere and need to access that string //you can cats your string to an array and then pass the index //number to key[]
 
 let newUserEmail = Array(newPatient.email())
 let password = Array(newPatient.password)
 
 //When you cast your string to an array the elements of the array //are Character so you would need to cast them into string otherwise //Xcode will compain. 
 
 let keys = app.keys
     keys[String(newUserEmail[0])].tap()
     keys[String(newUserEmail[1])].tap()
     keys[String(newUserEmail[2])].tap()
     keys[String(newUserEmail[3])].tap()
     keys[String(newUserEmail[4])].tap()
     keys[String(newUserEmail[5])].tap()       


Another answer, but for us the problem was the view was too close to another view that a Gesture recognizer on it. We found we needed the view to be at least 20 pixels away (in our case below). Literally 15 didn't work and 20 or more did. This is strange I'll admit, but we had some UITextViews that were working and some that were not and all were under the same parent and identical other positioning (and variable names of course). The keyboard on or off or whatever made no difference. Accessibility showed the fields. We restarted our computers. We did clean builds. Fresh source checkouts.


What fixed this problem for me was adding a 1 second sleep:

let textField = app.textFields["identifier"]
textField.tap()
sleep(1)
textField.typeText(text)

Had the same issue with Securetextfields. The connect hardware option in my Simulator was of, but still ran into the issue. Finally, this worked for me (Swift 3):

 let enterPasswordSecureTextField = app.secureTextFields["Enter Password"]
    enterPasswordSecureTextField.tap()
    enterPasswordSecureTextField.typeText("12345678")

참고URL : https://stackoverflow.com/questions/32184837/ui-testing-failure-neither-element-nor-any-descendant-has-keyboard-focus-on-se

반응형