Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Espresso click on specific words of text

In my espresso test I want to tap on a certain part of a text element with the idSwitchTextView . The full text reads " Are you a member? Login with email" When you click on the login with email it switches the view of the page.

When I use onView(withId(R.id.switchTextView)).perform(click()); The test passes but because there is initial text before the text I want to be clicked on it doesnt change view. How can I pin point and only touch the "Login with email" text?

like image 468
Billy Boyo Avatar asked Feb 22 '17 11:02

Billy Boyo


2 Answers

The only way I found was to find the point where to press and tell Espresso to press there. It seems really hard but actually I took the right spot at first try 3 times. It's more easy than it sounds.

I just did like this:

onView(withId(R.id.switchTextView)).perform(clickPercent(0.4F, 0.4F))

The reason is because my text is slightly in the top left part of the view. In this case, I'll suggest something like 0.5F, 0.8F since I suppose is the right part of the label that needs to be clicked.

To do that, I used clickPercent. A method copyed by this anwser.

I copy my Kotlin version in case someone will find it useful.

fun clickPercent(pctX: Float, pctY: Float): ViewAction {
    return GeneralClickAction(
            Tap.SINGLE,
            CoordinatesProvider { view ->
                val screenPos = IntArray(2)
                view.getLocationOnScreen(screenPos)
                val w = view.width
                val h = view.height

                val x = w * pctX
                val y = h * pctY

                val screenX = screenPos[0] + x
                val screenY = screenPos[1] + y

                floatArrayOf(screenX, screenY)
            },
            Press.FINGER,
            InputDevice.SOURCE_MOUSE,
            MotionEvent.BUTTON_PRIMARY)
}
like image 156
Filnik Avatar answered Sep 28 '22 04:09

Filnik


You can do like this

onView(withId(R.id.switchTextView(matches(withText(containsString("Login with email"))));
like image 39
ugurcmk Avatar answered Sep 28 '22 05:09

ugurcmk