Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to click the snackbar button in Espresso testing?

I don't believe that this is a dupe question. I am writing a simple Espresso test and part of it involves clicking a "Ok" button in a snackbar.

Espresso.onView(allOf(withId(android.support.design.R.id.snackbar_text), withText(R.string.permission_snackbar)))
            .check(matches(isDisplayed()));
Espresso.onView(withText("Ok")).perform(click());

This throws

android.support.test.espresso.PerformException: Error performing 'single click' on view 'with text: is "Ok"'. Caused by: java.lang.RuntimeException: Action will not be performed because the target view does not match one or more of the following constraints: at least 90 percent of the view's area is displayed to the user. Target view: "AppCompatButton{id=2131558552, res-name=snackbar_action, visibility=VISIBLE, width=264, height=144, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=684.0, y=53.0, text=Ok, input-type=0, ime-target=false, has-links=false}"

Any ideas?

like image 528
user user Avatar asked Oct 28 '15 01:10

user user


2 Answers

The RuntimeException seen here java.lang.RuntimeException: Action will not be performed because the target view does not match one or more of the following constraints: at least 90 percent of the view's area is displayed to the user.. The issue does, in fact come from a failure of the View to be fully displayed.

The issue is caused by a race condition. You are attempting to open the view, and during it's opening you are attempting to click it. If the timing isn't right, then less than 90% of the View will be available for the Espresso framework to click(). You may be able to resolve the issue by disabling animations, as recommended in The Espresso Setup Instructions

  • Navigate to you phone's Developer Options
  • Set the following
    • Window animation scale = 0.0x
    • Transition animation scale = 0.0x
    • Animator duration scale = 0.0x

My own testing indicates that you can get away with just setting the Transition Animation Scale to 0.0x. As you can imagine, this is a perfectly consistent solution to the race condition that you're experiencing.

like image 73
OYRM Avatar answered Nov 06 '22 03:11

OYRM


It can simply be found using the id snackbar_action:

onView(allOf(withId(android.support.design.R.id.snackbar_action)))
    .perform(click());
like image 3
Rémi F Avatar answered Nov 06 '22 03:11

Rémi F