简体   繁体   中英

How to do a swipe action to a test in espresso?

Espresso has the swipe action, I want to know if is possible to make a swipe left or right action until a text is visible on the screen. I mean if I have a Tab layout with a lot of tabs, I want to execute the swipe action until a Tab with an specific text is visible

This can be done in a just a loop that makes the swipe and then checks that this element is visible in a try/catch block until you reach the end of the pageview or the item is found.

If the end of the pageview is reached and the item is not found then you can do something like Assert.fail("The element has not been found.");

Try this code:

boolean found = false;
int i = 0;
while (!found && i < NUM_PAGES) {
    onView(withId(R.id.viewPager)).perform(swipeLeft());
    SystemClock.sleep(500);

    try {
        if (checkElementVisible()) {
            found = true;
        }
    } catch (Exception e) {
        // The search continues
    }
    i++;
}

if (!found) {
    Assert.fail("The element has not been found.");
}

You can swipe once and verify if your textView is displayed. If not, swipe again.

Or you can have a method in which you verify for your textview...and if "NoMatchingViewException" is thrown, you swipe.

Something like this(didn't test the code):

    public static boolean swipeUntilExists(int resourceId) {
    final ViewInteraction uiElement = onView(withId(resourceId));
    boolean isVisible = false;
    while (!isVisible) {
        try {

            // do swipe here

            uiElement.check(matches(isDisplayed()));
            isVisible = true;
        } catch (NoMatchingViewException e) {
            // do nothing here
        }
    }
    return isVisible;
}

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