Loading...
Loading...
Use this skill to choose the right idle-synchronization primitive in Compose UI tests — waitForIdle, awaitIdle, waitUntil(conditionDescription, timeoutMillis, condition), waitUntilNodeCount, waitUntilExactlyOneExists, waitUntilAtLeastOneExists, waitUntilDoesNotExist, runOnIdle, runOnUiThread, runWhenIdle, awaitAndRunWhenIdle, hasPendingWork, and IdlingResource. Explains what "idle" means (no pending recomposition or draw, every IdlingResource isIdleNow), the wall-clock vs test-clock timeout split, the Espresso/Robolectric strategy bridge, and why direct state reads from the test thread race the recomposer. If the user mentions "test is flaky", "test passes locally fails on CI", "Thread.sleep waiting for state", "Espresso IdlingResource", "ComposeTimeoutException waitUntil", "AndroidComposeUiTestTimeoutException", waitUntilExactlyOneExists, runOnIdle, runWhenIdle, or "register IdlingResource", use this skill.
npx skill4agent add skydoves/android-testing-skills synchronizing-with-idleComposeTestRuleComposeUiTest../testing-animations-deterministically/SKILL.md../controlling-the-test-clock/SKILL.mdThread.sleep(2000)ViewModelIdlingResourcerunOnIdlerunOnUiThreadrunWhenIdlewaitUntilwaitUntilExactlyOneExistswaitUntilNodeCountAndroidComposeUiTestTimeoutExceptionIdlingPolicies.setMasterPolicyTimeoutstate.firstVisibleItemIndex../testing-animations-deterministically/SKILL.mdmainClock.advanceTimeUntilMainTestClock../controlling-the-test-clock/SKILL.md../../debug/printing-the-semantics-tree/SKILL.md../../finders/finding-nodes-by-tag-text-content/SKILL.md../../interop/testing-with-espresso-interop/SKILL.mdandroidx.compose.ui:ui-testandroidx.compose.ui:ui-test-junit4runComposeUiTestComposeContestTestRulecreateComposeRule()androidx.compose.ui.test.junit4.v2.createComposeRulewaitUntilNodeCountwaitUntilExactlyOneExistswaitUntilAtLeastOneExistswaitUntilDoesNotExist@OptIn(ExperimentalTestApi::class)compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/ComposeUiTest.kt:174-186withFrameNanosMainTestClock.kt:36-41IdlingResourceisIdleNow == trueOkHttpRoomComposeIdlingResourcecompose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeIdlingResource.android.ktwaitForIdleComposeUiTest.ktComposeTestRule.jvmAndAndroid.kt| API | Effect | Timeout source |
|---|---|---|
| Blocks current thread until the three idle conditions hold. With | Wall clock — |
| | Same |
| Blocks until | Wall clock — per-call |
| | Wall clock |
| | Wall clock |
| | Wall clock |
| | Wall clock |
| | Wall clock (the inner |
| Posts a | None |
| | Wall clock |
| | Wall clock |
| Passive snapshot: are there awaiters on the main clock, snapshot changes, or recomposer pending work? Reliable only when | None |
| | Wall clock |
| API | Source | Default | Override |
|---|---|---|---|
| Wall clock — Espresso | 26 s | |
| Wall clock | 1000 ms per call | per-call |
| Test clock | 1000 ms per call | per-call |
| Wall clock | | |
waitUntiladvanceTimeUntilmainClock.advanceTimeUntilwaitUntilJob.isCompletedLaunchedEffectRobolectricIdlingStrategyIdlingPolicies.getMasterIdlingPolicy()setMasterPolicyTimeoutandroidx.test.espresso.IdlingResourceandroidx.compose.ui.test.IdlingResourceEspressoLinkcompose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/EspressoLink.android.ktEspresso (instrumentation tests)
│ withStrategy { … }
▼
EspressoLink ──implements──> androidx.test.espresso.IdlingResource
│
│ delegates isIdleNow() to ──> IdlingResourceRegistry
▼
IdlingResourceRegistry — Compose's registry
│
├── ComposeIdlingResource (recomposer + snapshot + frame-clock awaiters)
└── any rule.registerIdlingResource(...)RobolectricIdlingStrategyIdlingResourceinterface IdlingResource {
val isIdleNow: Boolean
fun getDiagnosticMessageIfBusy(): String? = null
}compose/ui/ui-test/src/jvmAndAndroidMain/kotlin/androidx/compose/ui/test/IdlingResource.kt:37-52getDiagnosticMessageIfBusy()Need to wait for… | Use
------------------------------------------|----------------------------------------------
A node count to stabilize | waitUntilNodeCount / waitUntilExactlyOneExists
A node to appear | waitUntilAtLeastOneExists
A node to disappear | waitUntilDoesNotExist
A Compose state condition | mainClock.advanceTimeUntil { state }
A non-Compose condition (Job, counter) | waitUntil(conditionDescription) { condition }
"Just settle the UI" | waitForIdle() (or runOnIdle for read+act)
External async work (HTTP, DB) | rule.registerIdlingResource(MyIdlingResource)
A paused-clock animation frame | mainClock.advanceTimeBy(...) -- different skill
A particular state.value to read safely | rule.runOnIdle { state.value }runOnIdlerunOnIdleval firstVisibleIndex = rule.runOnIdle { state.firstVisibleItemIndex }runOnIdlerunOnUiThreadrunWhenIdlerule.runWhenIdle {
val node = rule.onNodeWithTag("counter").fetchSemanticsNode()
assertEquals("3", node.config[SemanticsProperties.Text].first().text)
val rect = node.boundsInRoot
// ... more reads ...
}runOnIdlewaitForIdle()runWhenIdlerunOnIdlewaitForIdle()autoAdvance = truerunWhenIdlewaitUntilExactlyOneExists@OptIn(ExperimentalTestApi::class)
@Test fun snackbarAppears() {
rule.setContent { /* … triggers a snackbar after 200 ms … */ }
rule.onNodeWithTag("trigger").performClick()
rule.waitUntilExactlyOneExists(hasTestTag("snackbar"), timeoutMillis = 2_000)
rule.onNodeWithTag("snackbar").assertTextEquals("Saved")
}ComposeUiTest.kt:278ComposeUiTest.kt:301ComposeUiTest.kt:321ComposeUiTest.kt:334waitUntil { … }// SnackbarHostTest.kt:77-88
val job = scope.launch {
hostState.showSnackbar("1")
Truth.assertThat(resultedInvocation).isEqualTo("1")
hostState.showSnackbar("2")
Truth.assertThat(resultedInvocation).isEqualTo("12")
hostState.showSnackbar("3")
Truth.assertThat(resultedInvocation).isEqualTo("123")
}
rule.waitUntil { job.isCompleted }Job.isCompletedmainClock.advanceTimeUntil { job.isCompleted }JobIdlingResourceclass HttpIdlingResource(private val client: OkHttpClient) : IdlingResource {
override val isIdleNow: Boolean
get() = client.dispatcher.runningCallsCount() == 0
override fun getDiagnosticMessageIfBusy(): String? =
"${client.dispatcher.runningCallsCount()} HTTP calls still in flight"
}
@Before fun setUp() { rule.registerIdlingResource(HttpIdlingResource(client)) }
@After fun tearDown() { rule.unregisterIdlingResource(HttpIdlingResource(client)) }waitForIdlewaitForIdleisIdleNow == trueisIdleNowIdlingResource.kt:38-46Thread.sleep// WRONG
@Test fun successScreen() {
rule.setContent { App() }
rule.onNodeWithTag("login").performClick()
Thread.sleep(2_000)
rule.onNodeWithTag("dashboard").assertExists()
}
// WRONG because: Thread.sleep is unrelated to Compose's synchronization. It either over-
// waits (slowing the test) or under-waits (flake when CI is slow). Compose's own
// IdlingResource is already wired; just wait on the node directly.// RIGHT
@OptIn(ExperimentalTestApi::class)
@Test fun successScreen() {
rule.setContent { App() }
rule.onNodeWithTag("login").performClick()
rule.waitUntilExactlyOneExists(hasTestTag("dashboard"), timeoutMillis = 2_000)
rule.onNodeWithTag("dashboard").assertExists()
}waitUntil// WRONG
rule.waitUntil(timeoutMillis = 5_000) { state.value == Phase.Done }
// WRONG because: timeout is measured in wall clock and each iteration burns ~10 ms
// of real time on Thread.sleep(10) (ComposeUiTest.android.kt:899-902). For a Compose
// state condition, advanceTimeUntil drives the test clock and is deterministic.// RIGHT
rule.mainClock.advanceTimeUntil(timeoutMillis = 5_000) { state.value == Phase.Done }// WRONG
val i = state.firstVisibleItemIndex
assertEquals(2, i)
// WRONG because: the test thread races the recomposer. The read may observe a half-applied
// snapshot, especially right after a click or scroll. Compose's docs are explicit: state
// reads from outside the UI thread are not synchronized.// RIGHT
val i = rule.runOnIdle { state.firstVisibleItemIndex }
assertEquals(2, i)hasPendingWork()rule.mainClock.autoAdvance = false
rule.setContent { /* … */ }
rule.mainClock.advanceTimeByFrame()
rule.runOnUiThread { trigger = true }
assertTrue(rule.hasPendingWork()) // recomposition queued, no frame yet
rule.mainClock.advanceTimeByFrame()
assertFalse(rule.hasPendingWork()) // frame appliedComposeUiTest.kt:251-256IfisautoAdvance, the testing framework continuously processes pending work. In that scenario, calling this method acts as a momentary snapshot and will generally returntrue. It may briefly returnfalseif work is queued but the framework hasn't auto-advanced yet, making the result fleeting and unreliable for driving test logic.true
hasPendingWork()autoAdvance == true@Before fun setUp() {
IdlingPolicies.setMasterPolicyTimeout(60, TimeUnit.SECONDS)
}waitForIdlewaitUntilEspressoLinkRobolectricIdlingStrategymainClock.advanceTimeUntil { state }rule.waitUntil { state }runOnIdle { … }runOnUiThread { … }state.valuerunOnUiThreadrunOnIdleautoAdvance = falserunOnIdlewaitForIdle../testing-animations-deterministically/SKILL.mdrunWhenIdle { … }waitForIdlewaitUntilExactlyOneExistswaitUntilAtLeastOneExistswaitUntilDoesNotExistwaitUntil { onAllNodes(...).fetchSemanticsNodes().isNotEmpty() }conditionDescriptionhasPendingWork()autoAdvance == trueComposeUiTest.kt:251-256Thread.sleepwaitUntil*mainClock.advanceTimeUntilIdlingResourceThread.sleepIdlingResource@Before@AftergetDiagnosticMessageIfBusy()IdlingPolicies.setMasterPolicyTimeout(...)@BeforeThread.sleeprunOnIdle { … }grep -nP 'state\.\w+' src/androidTestwaitUntil { state.value … }mainClock.advanceTimeUntil { state.value … }waitUntilExactlyOneExistswaitUntilAtLeastOneExistswaitUntilDoesNotExistwaitUntilfetchSemanticsNodes()IdlingResource@Before@AfterhasPendingWork()autoAdvance == trueAndroidComposeUiTestTimeoutExceptionComposeTimeoutExceptionIdlingPoliciescompose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/ComposeUiTest.kt:174-260waitForIdleawaitIdlewaitUntilrunOnIdlerunOnUiThreadrunWhenIdleawaitAndRunWhenIdlehasPendingWorkcompose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/ComposeUiTest.kt:275-335waitUntilNodeCountwaitUntilExactlyOneExistswaitUntilAtLeastOneExistswaitUntilDoesNotExistcompose/ui/ui-test/src/jvmAndAndroidMain/kotlin/androidx/compose/ui/test/IdlingResource.ktIdlingResourcecompose/ui/ui-test/src/jvmAndAndroidMain/kotlin/androidx/compose/ui/test/IdlingResourceRegistry.jvmAndAndroid.ktcompose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeIdlingResource.android.ktcompose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/EspressoLink.android.ktandroidx.test.espresso.IdlingResourcecompose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/ComposeUiTest.android.kt:885-908waitUntilcompose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/AndroidSynchronization.android.ktrunOnUiThreadFutureTaskInstrumentation.runOnMainSynccompose/material3/material3/src/androidDeviceTest/kotlin/androidx/compose/material3/SnackbarHostTest.kt:77-88rule.waitUntil { job.isCompleted }../controlling-the-test-clock/SKILL.mdMainTestClockadvanceTimeUntil../testing-animations-deterministically/SKILL.md../../patterns/structuring-a-compose-test/SKILL.md../../debug/printing-the-semantics-tree/SKILL.md