Search code examples
swiftuialertcontrollerxcuitest

How can I add an accessibilityIdentifier to a textField within a UIAlertController


Using XCUITest I'm struggling to locate a textField on an UIAlertController which is used to add items to a list.

I've added an accessibilityIdentifier to the alert itself, but would like to add one to the textField if possible too as so far my test (which is part recorded) can only located the field the first time the function is run. The second time it opens the alert to add an item to a list it can't find focus on the textField.

The UIAlertConroller looks like this:

let alert = UIAlertController(title: "Add A Task", message: "Add new", preferredStyle: .alert)
        alert.view.accessibilityIdentifier = "Add Task Panel" // Added this identifier to help with UI tests
        alert.addTextField(configurationHandler: nil)
        alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
        alert.addAction(UIAlertAction(title: "Add", style: .default, handler: { [weak self] (action) -> Void in

The test function looks like this, but was partially generated using the 'record' functionality, so not ideal as i feel there must be a better way to identify the textField (there's only one on screen).

func addTextToOpenPopUp(textToAdd: String) {
        
        
        let popUpTextField = app.alerts["Add Task Panel"].scrollViews.otherElements.collectionViews.cells
            .children(matching: .other).element
            .children(matching: .other).element
            .children(matching: .other).element
            .children(matching: .other).element(boundBy: 1)
            .children(matching: .textField).element
        
        popUpTextField.tap()
        popUpTextField.typeText(textToAdd)
    }

I've spent hours trying to find a way to add identifiers to components within an alert, but can't find any answers.


Solution

  • You've missed the configurationHandler, it's used specifically to modify your text field:

    alert.addTextField(configurationHandler: { textField in
        textField.accessibilityIdentifier = "Task Text Field"
    })