Search code examples
iosios-ui-automation

UIAutomation skipping lines


I am having a very difficult time with UIAutomation not doing things even if I give long delays. In the code snippet below UIALogger.logWarning("Alert with title ’" + title + "’ encountered!"); is not being logged but the tap immediately after it is happening.

Sometimes all 3 test messages print out but usually only the first two.

As you can see I have tried adding delays and also test messages.

UIALogger.logMessage("Tap Signup button");
var signupButton = window.buttons()["Signup Button"];
if (signupButton.checkIsValid())
{
    signupButton.tap();
    UIALogger.logMessage("test message");
    target.delay(3);
    if (app.alert())
    {  
        target.delay(3);
        UIALogger.logMessage("test message 2");
        UIATarget.onAlert = function onAlert(alert) 
        {
            target.delay(10);
            UIALogger.logMessage("test message 3");
            var title = alert.name();
            UIALogger.logWarning("Alert with title ’" + title + "’ encountered!");
            alert.buttons()[0].tap();
        }
    }
    target.delay(1);
}
else
{
    UIALogger.logError("Signup Button not found");
}

I have this exact same code:

    UIATarget.onAlert = function onAlert(alert) 
    {
        var title = alert.name();
        UIALogger.logWarning("Alert with title ’" + title + "’ encountered!");
        alert.buttons()[0].tap();
    }

elsewhere and it works without problems. I really have no idea what is going on. Do you?


Solution

  • The problem here is that your alert handler is being set after the alert fires. The times that you are seeing all three messages show up are probably after an alert has already been fired in the app and was caught by the previous alert handler. What you'll want to do is declare your alert handler before you use it. My suggestion for you would be to do this as the first code that executes after your import statements. Alerts can happen at any time and it's best to get your handler in place as soon as possible to avoid strange behavior caused by race conditions.

    You'll also want to return true if you're dismissing the alert yourself, otherwise the Instrument will try to tap the button after your handler returns even though it no longer exists. This will cause errors and/or strange behavior in the automation.