Issue
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?
Solution
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 }
}
Answered By - cutiko
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.