Search code examples
androidkotlinandroid-jetpack-composecompose-recomposition

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


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


Solution

  • 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.