简体   繁体   中英

How do I enter text in an alert textfield using Xcode UI Automation testing

This problem is really bugging me. Having read the official documentation, the book by Jonathan Penn and all the online tutorials I can find. I have built a really simple app to learn about UI Testing but am getting stumped at the first step. Its a todo list app. I click on the UIBarButtonItem button which displays a dialog with a UITextField and two button, OK and Cancel. Here is the IBAction.

@IBAction func showDialog(sender: UIBarButtonItem) {
    println("showDialog")
    var inputTextField: UITextField?
    var alert:UIAlertController
    alert = UIAlertController(title: "New Item", message: "Type item below", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
        textField.placeholder = "Item name"  // need to choose correct keyboard and capitalise first letter of each word.
        inputTextField = textField
    })
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
        if let itemName = inputTextField?.text {
            println(itemName)
            self.items.append(itemName)
            self.tableView.reloadData()
        }
    }))
    alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)
}

I have tried to write a UI Automation test by recording then adding the alert handler but it won't work. Here is my testing script.

var target = UIATarget.localTarget();

UIALogger.logWarning('script started');

target.frontMostApp().navigationBar().rightButton().tap();

UIATarget.onAlert = function onAlert(alert) {
    var title = alert.name();
    UIALogger.logWarning("Alert with title ’" + title + "’ encountered!");
    target.frontMostApp().keyboard().typeString("Cheese");
    alert.buttons()["OK"].tap();
    return true;
}

What am I doing wrong?

After much searching I found the answer. The onAlert function simply returns true if we want to interact with the alert and false if we simply want to dismiss it.

var target = UIATarget.localTarget();
var app = target.frontMostApp();
var window = app.mainWindow();
window.navigationBar().rightButton().tap();

UIATarget.onAlert = function() {
    return true;
}

app.keyboard().typeString("Cheese");
app.alert().buttons()["OK"].tap();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM