Is there anyway to force recomposition in tests? I want to ensure something is executed as a `Launch...
c
Is there anyway to force recomposition in tests? I want to ensure something is executed as a
LaunchedEffect
but I can't find a way to emphasise that with a test.
I've got something like this right now but it feels like there might be a nicer way to achieve it:
Copy code
@Test
fun onlyInvokesCallbackOnce() {
   var count = 0

   rule.setContent {
      var targetSize by remember { mutableStateOf(0.dp) }
      val size by animateDpAsState(targetValue = targetSize)
      Box(modifier = Modifier.size(size)) {
         MyComposable {
            count++
         }
      }
      LaunchedEffect(Unit) { targetSize = 100.dp }
   }

   rule.waitForIdle()

   assertEquals(1, count)
}
h
Maybe something like this?
Copy code
val composeTestRule: ComposeTestRule = createEmptyComposeRule()
protected lateinit var scenario: ActivityScenario<HiltComponentActivity> // replace if needed

@Before
override fun setup() {
    super.setup()
    scenario = ActivityScenario.launch(HiltComponentActivity::class.java) // replace if needed
}

@Test
fun onlyInvokesCallbackOnce() {
    var count = 0
    val inc: () -> Unit = { count++ }
    scenario.onActivity { activity -> activity.setContent { Test(inc) } }
    assertEquals(1, count)

    scenario.recreate()
    scenario.onActivity { activity -> activity.setContent { Test(inc) } }

    assertEquals(2, count)
}

@Composable
fun Test(inc: () -> Unit) {
    var targetSize by remember { mutableStateOf(0.dp) }
    val size by animateDpAsState(targetValue = targetSize)
    Box(modifier = Modifier.size(size)) {
        MyComposable {
            inc()
        }
    }
    LaunchedEffect(Unit) { targetSize = 100.dp }
}
Maybe not 😅 I use this to test my
rememberSaveable
with custom Saver but I may have misunderstood your problem.
z
For testing
rememberSaveable
you might want to use StateRestorationTester instead.
As for forcing recomposition, that sounds potentially sketchy, but you could use currentRecomposeScope
h
Thanks Zach! I didn't find this documentation, I will check it 🙂