'What Are Some Best Practices When Asserting iOS Elements Are Displayed?

I'm trying to write my first UI Automation test for an iOS app with Appium/Python.

I find that when I list 10 assertions like the one below, I get very inconsistent results ... sometimes it passes, but it usually fails the third assertion, sometimes it fails the eighth.

assert driver.find_element_by_name('Settings').is_displayed()

I've also tried to use waits:

driver.wait_for_element_by_name_to_display('Settings')
assert driver.find_element_by_name('Settings').is_displayed()


Solution 1:[1]

I don't know python code, i am showing how i am doing it in java. Hope you can convert it in python code.

Create a method like following:

public boolean isElementDisplayed(MobileElement el){
     try{
        return el.isDisplayed();
     }catch(Exception e){
        return false;
     }
}

Then you can check if the element is displayed by calling above method:

MobileElement element = driver.findElementById('element id');
boolean isElementVisible = isElementDisplayed(element);
if(isElementVisible){
   //element is visible
}else{
   //element is not visible
}

If you don't use try catch, then the exception will be thrown when element is not found.

Solution 2:[2]

There is a good util class that can be used for this EC. Hereès the link to the git documentation

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

Then you can use it this way to detect if an element is present:

from appium.webdriver.common.mobileby import MobileBy
# time in seconds
timeout = 10
wait = WebDriverWait(driver, timeout)
wait.until(EC.presence_of_element_located((MobileBy.NAME, 'Settings'))

If you need to detect present and visible use:

wait.until(EC.visibility_of_any_elements_located((MobileBy.NAME, 'Settings'))

Solution 3:[3]

You can wait until target element located as below.

https://github.com/appium/python-client/blob/6cc1e144289ef3ee1d3cbb96ccdc0e687d179cac/test/functional/android/helper/test_helper.py

Example:

from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

TIMEOUT = 3
WebDriverWait(self.driver, TIMEOUT).until(
    EC.presence_of_element_located((MobileBy.ACCESSIBILITY_ID, 'Text'))
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Nic Laforge
Solution 3 Mori