4

Are there any tools or way to test recomposition happens in a piece of code or not in Jetpack compose?

z.g.y
  • 5,512
  • 4
  • 10
  • 36

1 Answers1

4

There is an example here in the official Compose Testing docs on how you can test if a recomposition takes place, by using composeTestRule.setContent, and in it track the state with a variable visible from the test.

Then you change the state from the test and assert that the tracking variable is equal to the expected state.

@Test
fun counterTest() {
    val myCounter = mutableStateOf(0) // State that can cause recompositions
    var lastSeenValue = 0 // Used to track recompositions
    composeTestRule.setContent {
        Text(myCounter.value.toString())
        lastSeenValue = myCounter.value
    }
    myCounter.value = 1 // The state changes, but there is no recomposition

    // Fails because nothing triggered a recomposition
    assertTrue(lastSeenValue == 1)

    // Passes because the assertion triggers recomposition
    composeTestRule.onNodeWithText("1").assertExists()
}

This example is used to show an edge-case in Compose-Testing for when you don't use methods for UI synchronization in your test (like e.g. onNodeWithText().assertExists()), but I think it could also be usable for your problem.

arne.jans
  • 3,798
  • 2
  • 22
  • 27
  • Thanks for your answer @arene.jans So if I want to test recomposition happens or not on a piece of code, I should write a UI test for it? – Sepideh Vatankhah Feb 18 '22 at 09:43
  • 1
    Sorry for the late answer. A UI test would be a way to systematically test your code for recomposition, yes. If you simply want to know when a recomposition takes place, put some logging-calls in the composable-function you want to investigate. – arne.jans Apr 08 '22 at 16:19