I have a UI with multiple UITextFields that I want to test by clearing their contents and typing new values. However, only the first field can be changed in a UI test; subsequent fields can be cleared (if their clear button is enabled), but they can't be typed into (using XCUIElement.typeText()), because the test Failed to synthesize event: Neither element nor any descendant has keyboard focus. How can I edit multiple text fields in a given UI test function?
I've followed the advice in a couple of different UI testing questions:
- Xcode UI Testing How to type text into custom class text fields
- UI Test deleting text in text field
- UI Testing Multiple UITextFields - accessibility was disabled in one of the fields
The UI:
The ViewController:
class ViewController: UIViewController {
    @IBOutlet weak var field1: UITextField!
    @IBOutlet weak var field2: UITextField!
    @IBAction func submit(_ sender: Any) {
        let actionVC = UIAlertController(title: "You did it!",
                                         message: "\(field1.text ?? ""), \(field2.text ?? "")",
                                         preferredStyle: .alert)
        actionVC.addAction(UIAlertAction(title: "Awesome!", style: .default, handler: nil))
        present(actionVC, animated: true, completion: nil)
    }
}
The test:
class TextFieldTesterUITests: XCTestCase {
    func testReplaceTextInMultipleTextFields() throws {
        let app = XCUIApplication()
        app.launch()
        let field1TextField = app.textFields["Field 1"]
        field1TextField.tap()
        app.buttons["Clear text"].tap()
        field1TextField.typeText("Oh")
        let field2TextField = app.textFields["Field 2"]
        field2TextField.tap()
        app.buttons["Clear text"].tap() // <-- 
        field2TextField.typeText("Susanna")
        app.staticTexts["Button"].tap()
        app.alerts["You did it!"].scrollViews.otherElements.buttons["Awesome!"].tap()
    }
}
The error:


