DEV Community

Cover image for Test Internal state in Compose Screenshot validation using CompositionLocal
Aniket Bhoite
Aniket Bhoite

Posted on Edited on

Test Internal state in Compose Screenshot validation using CompositionLocal

Compose Preview Screenshot Testing is a new screenshot testing framework from the Google. As of writing, it is still in the Alpha stage (v0.0.1-alpha16).

I was trying it out in a simple TO-DO app project and I came across a use case that this testing where this framework falls short. Later I figured out a workaround. I did not find any solution on the internet or by AI.

So here it is,
I have a TaskItem Composable with Title and Description texts, Description is hidden by default and only visible after user clicks on that item.


@Composable
fun TaskItem(
    id: Long,
    title: String,
    isCompleted: Boolean,
    onToggle: () -> Unit
) {

    var isExpanded by remember { mutableStateOf(false) }

    val hasDescription = !description.isNullOrBlank()

    Row(
        modifier.clickable{ isExpanded = !isExpanded }
    ) {
        Text(
            text = title,
            ....
        )
        ....
        AnimatedVisibility(visible = isExpanded && hasDescription) {
            Text(
                text = description ?: "",
                ..
            )
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

I can take screenshot of this TaskItem in a default state directly.

@PreviewTest
@Preview
@Composable
fun TaskItemNotCompletedPreview() {
    WeekendtasksTheme(dynamicColor = false) {
        TaskItem(
            id = 2,
            title = "Active task",
            isCompleted = false,
            onToggle = {},
            description = null
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

And I get something like this

Active TODO Item screenshot

But how do I test description expanded test? One way is to pass the default expanded value from the outside of a composable. But then we are exposing internal state of a composable to the outside. We should keep the state as close to the composable as possible. This is especially important while creating Compose UI libraries.

//Incorrect way ❌❌❌
@Composable
fun TaskItem(
    id: Long,
    title: String,
    isCompleted: Boolean,
    onToggle: () -> Unit,
    expanded: Boolean = false
) {

    var isExpanded by remember { mutableStateOf(expanded) }

    val hasDescription = !description.isNullOrBlank()

    Row(
        modifier.clickable{ isExpanded = !isExpanded }
    ) {
        Text(
            text = title,
            ....
        )
        ....
        AnimatedVisibility(visible = isExpanded && hasDescription) {
            Text(
                text = description ?: "",
                ..
            )
        }
    }
}


@PreviewTest
@Preview
@Composable
fun TaskItemNotCompletedExpandedPreview() {
    WeekendtasksTheme(dynamicColor = false) {
        TaskItem(
            id = 2,
            title = "Active task",
            isCompleted = false,
            onToggle = {},
            description = null
            expanded = true
        )
    }
}

Enter fullscreen mode Exit fullscreen mode

I don't prefer this approach. So what to do now? When testing with Roborazzi we can access the node and perform OnClick and then take a screenshot but in Compose Preview screenshot testing we use Preview Composables, so there is no direct way to perform OnClick.

So I got the idea to use CompositionLocal for the initial default value. Here's how:


internal val LocalExpansion = staticCompositionLocalOf { false }


@Composable
fun TaskItem(
    id: Long,
    title: String,
    isCompleted: Boolean,
    onToggle: () -> Unit
) {

    // Default value from CompositionLocal
    val localExpansion = LocalExpansion.current

    var isExpanded by remember { mutableStateOf(localExpansion) }

    val hasDescription = !description.isNullOrBlank()

    Row(
        modifier.clickable{ isExpanded = !isExpanded }
    ) {
        Text(
            text = title,
            ....
        )
        ....
        AnimatedVisibility(visible = isExpanded && hasDescription) {
            Text(
                text = description ?: "",
                ..
            )
        }
    }
}

@PreviewTest
@Preview
@Composable
fun TaskItemWithDescriptionExpandedPreview() {
    WeekendtasksTheme(dynamicColor = false) {
        CompositionLocalProvider(LocalExpansion provides true) {
            TaskItem(
                id = 6,
                title = "Task with expanded description",
                isCompleted = false,
                onToggle = {},
                description = "This is a longer description that provides more context about the task. It shows what the expanded view looks like.")
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

And we have a screenshot of expanded state

Task item with expanded state with description

Compose Preview Screenshot testing is still at the alpha stage, so there is still a chance that Google Android team will provide an official and correct way to achieve this.

If you know a better way to do this, please do comment or reach out to me. I will either update this blog or remove it completely if this turns out not to be the right approach.

I'm currently looking for a new role as a Senior Android Engineer. If you know of a team that's hiring, or would like to connect, please reach out to me at [aniketbhoite1203@gmail.com] or via LinkedIn. Thank you!

AI disclosure: AI was used only for grammar correction.

Top comments (2)

Collapse
 
userxnom profile image
Abdullah Naseer •

The CompositionLocal route is a neat workaround for the alpha limitation — the preview can force the expanded state without changing the production default. The tradeoff I'd watch is that the expanded state is now invisible to the caller, so a test can only set the starting value, not drive the toggle itself. Did you consider hoisting isExpanded up to the list or ViewModel instead, so the screenshot test sets it directly and the toggle path gets exercised too?

Collapse
 
aniketbhoite profile image
Aniket Bhoite •

Expanded state should be invisible to the caller. I don't want to hoist the expanded state to the caller composable that is why the workaround.