1

I have a composable that set the background color and I would like to test that.

@Composable
fun MyComposableButton(
    enabledColor: Color,
    disableColor: Color,
    isEnabled: Boolean = true,
) {
    val buttonBackgroundColor = if (enabled) enabledColor else disableColor
    Button(
        ...
        enabled = enabled,
        colors = ButtonDefaults.textButtonColors(
            backgroundColor = buttonBackgroundColor
        )
    ) { ... }
}

I'm expecting to write a tests like: verifyEnabledBackgroundColor and verifyDisabledBakcgroundColor.

I can't find any assertion directly available on the compose testing, and when trying to create my own I find that the SemanticMatcther uses a SemanticNode, but the constructor is internal for the latest so that is no go.

I try to mock the Color but I couldn't and according to this answer high API level would be required, which is a no for my project.

How can I test setting the background color for a composable?

cutiko
  • 8,436
  • 3
  • 41
  • 53

1 Answers1

1

After a lot of trials and errors, I found a way to do it. There is an extension captureImage that has the color space. With that, we can find the color name and make an equal assertion.

It has some limitations though: it is the surface underlying the node, so multiple nodes or gradients maybe won't work.

fun SemanticsNodeInteraction.assertBackgroundColor(expectedBackground: Color) {
    val capturedName = captureToImage().colorSpace.name
    assertEquals(expectedBackground.colorSpace.name, capturedName)
}

I made an extension for reusability, for example:

composeTestRule.setContent {
    ...
}

composeTestRule.onNodeWithText(someText).assertBackgroundColor(YourColor)

Beware, this might be working because in the testing we are making sure to pass our theme:

composeTestRule.setContent {
    OurSuperCoolTheme { //your compose }
}
cutiko
  • 8,436
  • 3
  • 41
  • 53
  • Man, it does not do the job :). It returns just the colorspace name which will be technically same for all colors. Test it with colors :). Tested it, not working. – Pietrek Jan 26 '22 at 06:59
  • @Pietrek thanks for letting me know, going to take a look at it – cutiko Jan 26 '22 at 11:52
  • 1
    no problem, if I find the solution I will post the answer here. Fingers crossed :) – Pietrek Jan 27 '22 at 12:36