skip to content

In a Compose UI test, when do you need waitUntil instead of the rule's automatic idling, and how does it differ from mainClock.advanceTimeUntil?

level: middleimportance: should knowfreq 48%

answer

  1. what counts as idle for Compose
  2. work on other threads is invisible
  3. polls a condition, sleeping between checks
  4. wall clock versus test clock
  5. default timeout 1_000 ms, ComposeTimeoutException

basics

~20 s

Use waitUntil when the UI waits on work Compose cannot see, such as a background load. It polls a condition until a wall-clock timeout (1,000 ms by default); mainClock.advanceTimeUntil steps the virtual test clock and suits only clock-driven Compose state.

solid answer

~40 s

Each action and assertion waits until Compose is idle: no pending recompositions, frames, layout passes or busy registered idling resources. A repository loading on a background thread is none of those, so `waitForIdle()` can return while the rehearsal list still shows its loading state. `composeTestRule.waitUntil(timeoutMillis = 5_000) { ... }` polls my condition, advancing a frame per iteration when `autoAdvance` is on and sleeping between checks, and throws `ComposeTimeoutException` when the wall-clock timeout passes; the default is 1,000 ms. `mainClock.advanceTimeUntil` instead steps the virtual clock frame by frame, with its timeout in test-clock time, so it suits state driven by that clock, like an animation or a `LaunchedEffect` delay. For a reusable signal I can register a Compose `IdlingResource` instead.

code

kotlin · 15 lines
kotlin
@OptIn(ExperimentalTestApi::class)
@Test
fun rehearsalsAppearAfterBackgroundLoad() {
    composeTestRule.setContent { RehearsalScreen(repository = slowFakeRepository) }

    // The fake repository answers on a background thread the test clock cannot see
    composeTestRule.waitUntil(timeoutMillis = 5_000) {
        composeTestRule.onAllNodesWithTag("rehearsal-row")
            .fetchSemanticsNodes().isNotEmpty()
    }
    // The same wait with the 1.12 helper, still experimental
    composeTestRule.waitUntilAtLeastOneExists(hasTestTag("rehearsal-row"), timeoutMillis = 5_000)

    composeTestRule.onAllNodesWithTag("rehearsal-row").assertCountEquals(3)
}

go deeper

for a junior

Recall that Compose tests wait for idle automatically, and that waitUntil exists for things that finish later than that.

for a middle

Explain what Compose counts as idle, why background-thread work is invisible to it, and how waitUntil's wall-clock timeout differs from advanceTimeUntil's test-clock timeout.

for a senior

Diagnose a test that passes locally and times out on CI: choose between a raised timeout, a Boolean condition, a clock advance or a registered idling resource.

for a principal

Decide how a team exposes background work to tests, one shared idling resource or injected test dispatchers, so suites stay fast without ad hoc waits.

## What the rule already waits for Compose tests are synchronized by default. Before every action and assertion, the test rule (or `runComposeUiTest`) waits until the UI is idle. Idle means, roughly: - no pending recompositions or snapshot changes; - no animation or other code waiting for a frame from the test clock; - no pending `setContent`, measure or layout pass; - every `IdlingResource` registered with `registerIdlingResource` reports `isIdleNow == true`. To reach that state the rule advances a **virtual clock**, `mainClock`, so animations finish instantly instead of in real time. `waitForIdle()` runs the same wait explicitly. ## What it cannot see The definition above is about Compose's own work. It does not include: - a repository call running on another dispatcher or thread pool; - a network request in an HTTP client; - a coroutine suspended in `delay(...)` while it waits; the Android docs' example shows "Loading..." still on screen after `setContent`, until the test advances the clock past the delay; - anything posted by code the test framework has no hook into. So for a choir-rehearsal screen that loads its list on a background thread, `onAllNodesWithTag("rehearsal-row").assertCountEquals(3)` can run while the list is still empty, pass on a fast laptop and fail on a slow CI emulator. ## waitUntil `ComposeTestRule.waitUntil(timeoutMillis: Long = 1_000, condition: () -> Boolean)` blocks until `condition` returns `true`: 1. On the v2 rules it first runs coroutines already queued on the test scheduler. 2. While the condition is `false`, it advances `mainClock` by one frame if `autoAdvance` is on, then sleeps briefly so the device can run measure, draw and other asynchronous work. 3. If the condition is still `false` after `timeoutMillis` of **wall-clock** time, it throws `ComposeTimeoutException` with a message like "Condition still not satisfied after 1000 ms". An overload takes a `conditionDescription` string that is added to that message. Two practical rules follow. Raise the timeout for slow environments; one second is tight on a CI emulator. And make the condition return a `Boolean` instead of asserting: `onAllNodesWithTag("rehearsal-row").fetchSemanticsNodes().isNotEmpty()` returns `false` while nothing matches, whereas `onNodeWithTag(...).assertExists()` inside the condition throws an `AssertionError` on the first check, and `waitUntil` does not catch it. In Compose 1.12 the rule also offers matcher-based helpers, `waitUntilAtLeastOneExists`, `waitUntilExactlyOneExists`, `waitUntilDoesNotExist` and `waitUntilNodeCount`. They are marked `@ExperimentalTestApi`, so a test opts in with `@OptIn(ExperimentalTestApi::class)`. ## mainClock.advanceTimeUntil `mainClock.advanceTimeUntil(timeoutMillis: Long = 1_000, condition: () -> Boolean)` looks similar but is a different tool: | | `waitUntil` | `mainClock.advanceTimeUntil` | |---|---|---| | What moves | real time passes; the clock advances one frame per check if `autoAdvance` is on | the virtual clock, one frame per check | | Timeout measured in | wall-clock milliseconds | test-clock milliseconds | | Lets the device draw between checks | yes | on Android, measure and layout run, draw does not | | Good for | background loads, anything outside Compose | animations, `LaunchedEffect` delays, other clock-driven state | | Speed | slower, sleeps every iteration | fast, no real waiting | The library documentation recommends trying `advanceTimeUntil` first and resorting to `waitUntil` when the condition depends on something the clock does not drive. ## Reading a timeout When `waitUntil` gives up, the `ComposeTimeoutException` message says the condition was still not satisfied after the timeout. Two habits make that message useful: - Pass a description with the overload `waitUntil(conditionDescription = "three rehearsal rows", timeoutMillis = 5_000) { ... }`, so the failure names what was awaited instead of an anonymous lambda. - Print the tree right before the wait, or in a catch that rethrows, with `onRoot().printToLog(...)`; a list stuck on its loading row and an empty list point at different bugs. If the condition becomes true locally within a few hundred milliseconds but times out on CI, the load is slower there, not broken: raise the timeout or make the fake repository answer faster, rather than retrying the test. ## Registering an idling resource instead When one background mechanism is used across many tests, a Compose `IdlingResource` (`androidx.compose.ui.test.IdlingResource`, with `isIdleNow` and an optional `getDiagnosticMessageIfBusy()`) registered through `composeTestRule.registerIdlingResource(...)` makes every action and assertion wait for it automatically. Remember to unregister it. It is a separate interface from Espresso's own idling resources, though it plays the same role. ## What not to do - `Thread.sleep(2_000)`: slow and still flaky. - Waiting on a `CountDownLatch`: the Android docs warn this can behave unexpectedly because the test clock is not advanced while the thread blocks. - Swallowing a timeout by catching `ComposeTimeoutException`; a timeout is the test telling you the UI never reached the state.

  • The rehearsal list appears after a LaunchedEffect calls delay(1_500); which wait do you use?
    The delay runs on the composition's test scheduler, so the test clock drives it: `mainClock.advanceTimeBy(1_500)` or `mainClock.advanceTimeUntil(timeoutMillis = 2_000) { ... }` finish it in virtual time. `waitUntil` would also get there by advancing one frame per iteration, but slowly, and with the default 1,000 ms wall-clock timeout it may give up first.
  • When is a registered Compose IdlingResource better than waitUntil?
    When the same background mechanism, such as a shared work queue the app exposes to tests, sits behind many screens. Registering it once makes every action and assertion wait for it, and its `getDiagnosticMessageIfBusy()` explains a timeout. `waitUntil` is better for a one-off condition in one test.

  • waitForIdle also waits for repository calls on background threads
  • waitUntil's timeout counts test-clock time, so it never times out early
  • An assertExists inside the waitUntil condition is retried until it passes
  • Thread.sleep is an acceptable way to wait for a slow load
  • advanceTimeUntil is the right tool for waiting on a network response

Assumes Compose UI testing 1.12, where waitUntil is stable and its matcher helpers such as waitUntilAtLeastOneExists are still @ExperimentalTestApi.