Android Compose Unit testing - Toggle a Switch

Viewed 524

Given a button with a Modifier:

TextButton(modified = Modifier.testTag("abc123"))

when you want to create a test to click it, you do:

composeTestRule.onNodeWithTag("abc123").performClick()

but when I'm having a:

Switch(modifier = Modifier.testTag("abc123"))

I'm trying every single perform gesture but I can't get the Switch to toggle, and can't get any documentation from Android.

What's the correct way to toggle it automatically in order to test it?

2 Answers

I had issues toggling a switch with performClick(), but it turned out the switch wasn't visible on screen, performClick() will then simply click the coordinates (0,0) without any error.

So to ensure it's displayed first:

composeTestRule.onNodeWithTag("abc123")
   .assertIsDisplayed()
   .performClick()

OLD ANSWER (can still be used if you need to click something which is not displayed)

This seems to be a working way to toggle a material Switch in a Jetpack Compose test:

composeTestRule.onNodeWithTag("abc123")
   .performSemanticsAction(SemanticsActions.OnClick)

I don't know if you are still struggling with this, but the following seems to work for me:

composeTestRule
        .onNodeWithTag("abc123")
        .performGesture {  swipeLeft() } // or swipeRight to turn it on
Related