4

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?

Rafael Ruiz Muñoz
  • 5,333
  • 6
  • 46
  • 92

2 Answers2

1

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)
  • This is the same as `performClick()` – 3k- Feb 18 '22 at 14:19
  • if you check the code `performClick()` is doing an actual tap, so it's not _the same_, however it is probably expected to have the same effect. I've looked at this a bit more now and It seems that both `performClick()` and `performSemanticsAction(SemanticsActions.OnClick)` works fine in general on a `Switch`, I've tried to create a smaller test reproduce the scenario where only `performSemanticsAction` works but so far without luck... – Ulf Andersson Feb 20 '22 at 14:08
  • Alright - so it turns out in my case it simply wasn't displayed :) I'll edit my answer – Ulf Andersson Feb 21 '22 at 07:55
  • Thanks Ulf. .performSemanticsAction(SemanticsActions.OnClick) worked for me. Always nice to see people you know having the same problems – latsson May 03 '22 at 10:16
1

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
Ruben Veldman
  • 440
  • 5
  • 9