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?
To correct cutiko accepted answer :
Validating color of composable based on colorspace.name does not work since the returned value is just a name of the color space. In other words test will pass regardless of the actual color.
Actual solution:
If the purpose of the test is to distinguish if the actual color of the composable is correct, for instance in a case where the color of a composable changes dynamically we need to use method .readPixels which provide "ARGB values packed into an Int. "
example usage:
val array = IntArray(20)
composeTestRule.onNodeWithTag(TestTags.CONTENT_TEXT_FIELD_TAG).captureToImage()
.readPixels(array, startY = 500, startX = 200, width = 5, height = 4)
array.forEach { it shouldNotBe Colors().Red.convert(ColorSpaces.Srgb).hashCode() }
array.forEach { it shouldBe Colors().Pink.convert(ColorSpaces.Srgb).hashCode() }