Search code examples
iosios-ui-automation

Fetch UIElement by using accessibilityIdentifier in UIAutomation


I am using profiler and UIAutomation to write tests for my iOS app.

How can I fetch UIElement to whom I have assigned accessibilityIdentifier in code? Here is my problem. I have an Universal app that runs on iPad and iPhone. View is different on these devices. I have 2 slightly different Xib files. On iPhone i have ScrollBar containing UILabel. On iPad I have ScrollBar containing UIView containing UILabel. These labels are contacted to the same IBOutlet. I have assigned accessibilityIdentifier to the IBOutlet.

How can I fetch my label from JavaScript using accessibilityIdentifier? Can it be done with the same code on iPad and on iPhone?

Something like

var label = target.frontMostApp().mainWindow().elements()["myAccesibilityIdentifier"];
UIALogger.logMessage("Is label valid? " + label.isValid());

As a result I get Is label valid? false


Solution

  • In your automation code you can discern whether or not your running iPad vs iPhone (example)

    if(target.model()=="iPhone" || target.model() == "iPhone Simulator")
    {
        var phone = true;
        var pad   = false;
        var appName = app.name();
        UIALogger.logMessage("Testing device is: iPhone");
        UIALogger.logMessage("Logger says: " + target.model()); 
        UIALogger.logMessage("Application name: " + appName);
    }   
    else if(target.model() =="iPad" || target.model() == "iPad Simulator")
    {   
        var phone = false;
        var pad   = true;
        var appName = app.name();
        UIALogger.logMessage("Testing device is: iPad");
        UIALogger.logMessage("Logger says: " + target.model());
        UIALogger.logMessage("Application name: " + appName);
    }
    

    based on the variables phone/pad that I set in the example you can instruct your script how to find the element you are looking for.

    if(phone)
    {
        //var label = Path to element (phone)
    }
    else if(pad)
    {
        //var label = Path to element (pad)
    }
    

    I know the use of pad/phone together is redundant, but I did that originally to be safe in case a third type gets mixed into iOS development in the future (Just in case ;)).