https://kotlinlang.org logo
#compose
Title
# compose
z

Zhelyazko Atanasov

02/22/2024, 1:38 PM
Any idea how to test composable that doesn't emit UI? I have a composable function that just defines a
DisposableEffect
to register/unregister broadcast receiver. In some cases this composable function is part of the Composable tree and in others - it's not. I would like to write an instrumentation test to verify that the composable is not present in some scenarios. Essentially, I'd like to be able to do something like:
Copy code
nonUiComposable.assertDoesNotExist()
but I have no idea how can I match a composable that doesn't emit UI. Here's an example how such a composable looks like:
Copy code
@Composable
fun BroadcastListener(onBroadcastReceived: (Payload) -> Unit) {
    DisposableEffect(context) {
        registerReceiver(onBroadcastReceived)

        onDispose {
            unregisterReceiver()
        }
    }
}
z

Zach Klippenstein (he/him) [MOD]

02/22/2024, 3:33 PM
You’d need to mock out the receiver registrar somehow. This isn’t a compose-specific problem, you’d have to do the same to test a View that registered a receiver.
a

Albert Chang

02/22/2024, 4:19 PM
Or you can create a spy of the original context and then verify the function call.
z

Zhelyazko Atanasov

02/22/2024, 4:41 PM
This was just an example. I'm asking generally how can we check that a non-UI emiting composable is added or not to the tree? If we have code like this in our Composable screen:
Copy code
if (listenForUpdates) {
    BroadcastListener(...)
}
and
listenForUpdates
is
false
how can I test/validate that
BroadcastListener
wasn't added to the tree (essentially doesn't exist)
z

Zach Klippenstein (he/him) [MOD]

02/22/2024, 5:32 PM
If it’s not emitting anything, then it’s not adding anything to the tree
If your composable performs a side effect, and you want to verify that the side effect was performed, then you need some way to detect the side effect.
z

Zhelyazko Atanasov

02/22/2024, 5:43 PM
Ahaaa I see 🙂 I thought that all composables are added to the tree, regardless if they emit or not UI. Thanks for clarifying that.
z

Zach Klippenstein (he/him) [MOD]

02/22/2024, 5:54 PM
Well there’s the conceptual tree, which is just the call tree, and then there’s the slot table, where information about some composables is tracked depending on certain optimizations, then there’s the applier tree, which is the emitted tree of nodes that is the most concrete of any of these things. For Compose UI, there’s also the modifier tree and the semantics tree. None of these have exact 1:1 correspondence to each other, and the semantics tree is the only one that is directly testable by the Compose UI test library.