I have a UI with multiple UITextField
s 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:
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:
As @Thisura Dodangoda pointed out, this code runs correctly on iOS 14.0.1 and 14.3, and I confirmed that it runs correctly on the 15.0 beta simulators. It appears to be a problem only on iOS 14.5, and perhaps on other versions between 14.3 and 15.0.