8

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?

Bartek Lipinski
  • 30,698
  • 10
  • 94
  • 132
Billy Boyo
  • 819
  • 2
  • 12
  • 22

2 Answers2

5

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)
}
Filnik
  • 352
  • 1
  • 12
  • 33
3

You can do like this

onView(withId(R.id.switchTextView(matches(withText(containsString("Login with email"))));
ugurcmk
  • 702
  • 6
  • 10