Rafael Ruiz Muñoz
Rafael Ruiz Muñoz

Reputation: 5472

Android Compose Unit testing - Toggle a Switch

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?

Upvotes: 5

Views: 3143

Answers (2)

Ruben Veldman
Ruben Veldman

Reputation: 620

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

Upvotes: 1

Ulf Andersson
Ulf Andersson

Reputation: 183

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)

Upvotes: 2

Related Questions