בדיקת האנימציות

‫Compose offers ComposeTestRule that allows you to write tests for animations in a deterministic manner with full control over the test clock. כך תוכלו לאמת ערכי אנימציה ביניים. בנוסף, אפשר להריץ בדיקה מהר יותר מהמשך בפועל של האנימציה.

ComposeTestRule חושף את שעון הבדיקה שלו כ-mainClock. אפשר להגדיר את המאפיין autoAdvance כ-false כדי לשלוט בשעון בקוד הבדיקה. אחרי שמפעילים את האנימציה שרוצים לבדוק, אפשר להעביר את השעון קדימה באמצעות advanceTimeBy.

חשוב לשים לב שהפונקציה advanceTimeBy לא מזיזה את השעון בדיוק למשך הזמן שצוין. היא מעגלת אותו כלפי מעלה למשך הזמן הקרוב ביותר שהוא כפולה של משך הפריים.

@get:Rule
val rule = createComposeRule()

@Test
fun testAnimationWithClock() {
    // Pause animations
    rule.mainClock.autoAdvance = false
    var enabled by mutableStateOf(false)
    rule.setContent {
        val color by animateColorAsState(
            targetValue = if (enabled) Color.Red else Color.Green,
            animationSpec = tween(durationMillis = 250)
        )
        Box(Modifier.size(64.dp).background(color))
    }

    // Initiate the animation.
    enabled = true

    // Let the animation proceed.
    rule.mainClock.advanceTimeBy(50L)

    // Compare the result with the image showing the expected result.
    // `assertAgainGolden` needs to be implemented in your code.
    rule.onRoot().captureToImage().assertAgainstGolden()
}