Compose Multiplatform Ui Testing
ASecurityUse when writing or running Compose Multiplatform UI tests from commonTest - runComposeUiTest, androidx.compose.ui.test.v2, ExperimentalTestApi, onNodeWithTag, performClick, performTextInput, waitForIdle, waitUntil, mainClock, testing a screen with its ViewModel and a fake repository, iosSimulatorArm64Test, jvmTest, connectedAndroidDeviceTest or androidDeviceTest, migrating the deprecated v1 runComposeUiTest, or a UI test that passes on one platform but times out, sees stale state or cannot f...
- 17 stars
- 0 votes
- 0 copies
- 0 views
- Added December 4, 2026
Works with
Security analysis
100/100Pro scans all 3 files and shows the line behind each finding
npx -y skills add Kushpawan/kmp-mobile-skills --skill compose-multiplatform-ui-testing --agent claude-codeAre you the author of Compose Multiplatform Ui Testing?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/kushpawan-compose-multiplatform-ui-testing)---
name: compose-multiplatform-ui-testing
description: Use when writing or running Compose Multiplatform UI tests from commonTest - runComposeUiTest, androidx.compose.ui.test.v2, ExperimentalTestApi, onNodeWithTag, performClick, performTextInput, waitForIdle, waitUntil, mainClock, testing a screen with its ViewModel and a fake repository, iosSimulatorArm64Test, jvmTest, connectedAndroidDeviceTest or androidDeviceTest, migrating the deprecated v1 runComposeUiTest, or a UI test that passes on one platform but times out, sees stale state or cannot find a node on another.
license: Apache-2.0
compatibility: Kotlin Multiplatform project with Compose Multiplatform and org.jetbrains.compose.ui:ui-test. The v2 API needs Compose Multiplatform 1.11+. iOS runs need macOS with Xcode and a simulator runtime; Android runs need a device or emulator.
metadata:
category: testing
platforms: android, ios
---
# Compose Multiplatform UI testing
Write UI tests once in `commonTest` with `runComposeUiTest`, find nodes by `testTag`, and drive
time explicitly. Since Compose Multiplatform 1.11 the v2 API runs composition on a
`StandardTestDispatcher`, so nothing queued runs until the test synchronises. A test that relies on
eager execution is a flaky test waiting to happen.
## When to use
- Adding UI tests for a shared screen or component: what renders for a state, what a click or
text entry sends, what the screen does with its ViewModel and a fake repository.
- Setting up `ui-test` for the first time, or adding a target (iOS simulator, desktop JVM, Android
device, web).
- Migrating `androidx.compose.ui.test.runComposeUiTest` (deprecated in 1.11) to the v2 entry point.
- A UI test that misses an update, times out, or finds no node on one target only.
## When not to use
- ViewModel, use case or repository logic without UI: `kmp-testing-patterns`.
- Pixel comparison and golden images: `kmp-screenshot-testing`.
- Whole-app flows on a real device or simulator (navigation across screens, system dialogs, deep
links, the real UIKit view tree): `kmp-maestro-e2e`.
- Choosing and naming test tags across Compose, SwiftUI and E2E tools: `mobile-accessibility-test-ids`.
- An existing test that passes and fails without code changes: `kmp-flaky-test-triage`.
- An Android-only app with no shared UI: Google's
[testing-setup](https://github.com/android/skills/tree/main/testing/testing-setup) skill.
## Step 0 - Read the project first
| Find out | Where to look | Follow it |
|---|---|---|
| Compose Multiplatform version | `gradle/libs.versions.toml` (`compose-multiplatform`, `composeMultiplatform`, `org.jetbrains.compose` plugin) | below 1.11: v1 API only; 1.11+: v2 |
| Existing UI tests and their API | `grep -rn "runComposeUiTest\|createComposeRule" --include=*.kt` plus the import line | same entry point and helpers as the existing tests |
| Targets | `kotlin { }` block: `iosSimulatorArm64()`, `jvm()`, `wasmJs()`, `android {}` or `androidTarget()` | run every target that exists; do not add targets |
| Android plugin | `com.android.kotlin.multiplatform.library` (with `kotlin { android {} }`) or legacy `com.android.library` + `androidTarget()` | device-test setup differs, see the reference |
| Test tags | a `*Tags` / `*TestTags` object, `Modifier.testTag(` calls | reuse the constants; never type tag strings in tests |
| UI shape | stateless content composable (`state`, `onAction`) vs. screen that resolves its ViewModel | test the content composable first |
| Dispatchers and DI | `DispatcherProvider`, `Dispatchers.setMain` in tests, `koinViewModel()` | inject test dispatchers the way unit tests already do |
| Tasks | `./gradlew :<module>:tasks --all \| grep -iE "test\|connected"` | use the real task names in Verify |
Rules that follow:
- **CMP below 1.11, or the module's tests use v1:** keep `androidx.compose.ui.test.runComposeUiTest`
for consistency and tell the user v1 is deprecated from 1.11. Migrate only as its own change
(checklist in [references/setup-and-targets.md](references/setup-and-targets.md#migrating-v1-to-v2)).
- **CMP 1.11+ and no UI tests yet:** use `androidx.compose.ui.test.v2.runComposeUiTest`.
- Never add a second UI-test style (JUnit `createComposeRule` in `jvmTest` next to common tests)
unless the project already uses it for desktop-only tests.
## Workflow
### 1. Add the dependency and the targets
`org.jetbrains.compose.ui:ui-test` in `commonTest`, plus `compose.desktop.currentOs` in `jvmTest`
when there is a desktop target. Android needs extra device-test wiring; without it the common
tests never reach Android. Catalog entries and both Android plugin variants:
[references/setup-and-targets.md](references/setup-and-targets.md).
*Done when* `./gradlew :shared:compileTestKotlinIosSimulatorArm64` (or the JVM equivalent) compiles
an empty `@Test fun smoke() = runComposeUiTest { setContent { } }`.
### 2. Choose what deserves a UI test
UI tests are slower than unit tests. Keep them few and behavioural:
- **Content tests** (most of them): the stateless content composable with a literal `UiState` and a
recording `onAction`. They pin what renders per state and which action each control sends.
- **Screen tests** (one or two per screen): the real ViewModel with a fake repository, to prove the
wiring (state collection, effects, navigation callbacks).
- Not here: reducer logic (`kmp-testing-patterns`), pixels (`kmp-screenshot-testing`), multi-screen
journeys (`kmp-maestro-e2e`).
### 3. Write content tests
The notes example keeps its tags in one `TestTags` object (`notes_list`, `note_row_<id>`,
`empty_state`, `add_note_button`, `editor_*`). Tests read the constants, never literal strings.
```kotlin
@OptIn(ExperimentalTestApi::class)
class NotesListContentTest {
@Test
fun should_showEmptyState_when_thereAreNoNotes() = runComposeUiTest {
setContent {
AppTheme { NotesListContent(state = NotesListUiState(isLoading = false), onAddNote = {}, onOpenNote = {}) }
}
onNodeWithTag(TestTags.EMPTY_STATE).assertIsDisplayed()
onNodeWithTag(TestTags.NOTES_LIST).assertDoesNotExist()
}
@Test
fun should_openNote_when_rowIsClicked() = runComposeUiTest {
var openedId: Long? = null
val notes = listOf(Note(id = 7, title = "Groceries", body = "Milk", updatedAtEpochMillis = 0))
setContent {
AppTheme {
NotesListContent(
state = NotesListUiState(isLoading = false, notes = notes),
onAddNote = {},
onOpenNote = { openedId = it },
)
}
}
onNodeWithTag(TestTags.noteRow(7)).performClick()
waitForIdle() // `openedId` is plain Kotlin state: settle the UI before reading it
assertEquals(7L, openedId)
}
}
```
- Expression body (`= runComposeUiTest { }`) and nothing after it: the function returns a
`TestResult`, and on web the test only completes if that result is returned.
- Finders and `perform*` calls synchronise implicitly; reading your own variables does not.
- *Done when* every visible state of the screen (empty, list, loading, error) has one assertion
and every control has one "calls callback X" test.
### 4. Write one screen test with the ViewModel and a fake repository
```kotlin
@OptIn(ExperimentalTestApi::class, ExperimentalCoroutinesApi::class)
class NoteEditorScreenTest {
private val repository = FakeNoteRepository()
@BeforeTest fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) // viewModelScope runs eagerly
@AfterTest fun tearDown() = Dispatchers.resetMain()
@Test
fun should_saveNoteAndClose_when_saveIsClicked() = runComposeUiTest {
var done = false
val viewModel = NoteEditorViewModel(noteId = 0L, repository = repository)
setContent { AppTheme { NoteEditorScreen(noteId = 0L, onDone = { done = true }, viewModel = viewModel) } }
onNodeWithTag(TestTags.EDITOR_TITLE_FIELD).performTextInput("Groceries")
onNodeWithTag(TestTags.EDITOR_BODY_FIELD).performTextInput("Milk, eggs")
onNodeWithTag(TestTags.SAVE_NOTE_BUTTON).performClick()
waitForIdle()
assertEquals(listOf("Groceries"), repository.saved.map { it.title })
assertTrue(done)
}
}
```
- Pass the ViewModel in (the screen's default `koinViewModel()` is then unused). If the screen has
no such parameter, start Koin with a test module and `stopKoin()` in `@AfterTest`.
- The fake is a hand-written class in `commonTest` (MockK does not compile for iOS).
- To assert an in-flight state (save disabled while saving), use a `StandardTestDispatcher` for
Main and a fake gated on a `CompletableDeferred`; that pattern, the fake and the Koin variant are
in [references/notes-test-examples.md](references/notes-test-examples.md).
### 5. Synchronise on purpose
Who runs the work decides how the test advances it:
| Work | Runs on | Advance it with |
|---|---|---|
| Composition, `LaunchedEffect`, `rememberCoroutineScope` | the test's `StandardTestDispatcher`, driven by `mainClock` | `waitForIdle()` / `awaitIdle()`; finders do it implicitly |
| `delay()` inside an effect, debounce in the UI | same scheduler, but idling does not wait for delays | `mainClock.advanceTimeBy(ms)` |
| Animations | `mainClock` (`autoAdvance = true` by default) | set `mainClock.autoAdvance = false`, then `advanceTimeByFrame()` / `advanceTimeBy(ms)` to stop mid-way |
| `viewModelScope` (`Dispatchers.Main`) | whatever `Dispatchers.setMain` installed | Unconfined: already ran. Standard: `scheduler.runCurrent()` / `advanceUntilIdle()`, then `waitForIdle()` |
| Hard-coded `Dispatchers.IO` / `Default` | real threads | inject a dispatcher; last resort `waitUntil(timeoutMillis = 5_000) { ... }` |
- `waitUntil` and `waitUntilExactlyOneExists(hasTestTag(...))` poll in **wall-clock** time (default
1 s). Use them only for work no test scheduler controls.
- Default test timeout is 60 s. On 1.13+ change it with
`runComposeUiTest(ComposeUiTestConfig(testTimeout = 2.minutes)) { }`; the old
`runComposeUiTest(effectContext, runTestContext, testTimeout)` overload is deprecated there.
### 6. Find nodes the stable way
- `onNodeWithTag(tag)` for one node, `onAllNodesWithTag(tag).assertCountEquals(n)` for lists.
- Rows of a lazy list may not be composed yet: scroll first with
`onNodeWithTag(TestTags.NOTES_LIST).performScrollToNode(hasTestTag(TestTags.noteRow(42)))`.
- A tag on a parent with merged children: query text inside it with `useUnmergedTree = true`.
- Text matchers (`onNodeWithText`) only for asserting copy, never for locating controls: strings
change with locale and Dynamic Type truncation.
- Debug a missing node with `println(onRoot().printToString())`; it works on every target.
### 7. Run on every target the module has
Run the task per target (Quick reference). A UI test that ran only on the JVM is not done.
## Quick reference
| Target | Task | Notes |
|---|---|---|
| iOS simulator | `:shared:iosSimulatorArm64Test` | macOS + Xcode; device targets cannot run tests; `iosX64` was removed in CMP 1.11 |
| Desktop JVM | `:shared:jvmTest` | needs `compose.desktop.currentOs` in `jvmTest` |
| Android | `:shared:connectedAndroidDeviceTest` (legacy `androidTarget()`: `connectedAndroidTest`) | device or emulator; needs the device-test wiring. Common UI tests do **not** run as Android host/local tests (`testAndroidHostTest`, `testDebugUnitTest`) |
| Web | `:shared:wasmJsTest` | only if the module has `wasmJs()` |
| API | Use |
|---|---|
| `androidx.compose.ui.test.v2.runComposeUiTest { }` | entry point, CMP 1.11+; Experimental, keep `@OptIn(ExperimentalTestApi::class)` |
| `androidx.compose.ui.test.runComposeUiTest { }` | v1, `UnconfinedTestDispatcher`; deprecated from 1.11 |
| `ComposeUiTestConfig(effectContext, runTestContext, testTimeout)` | 1.13+ configuration object; on iOS, desktop and web setting `inputMode`, `failurePolicy` or `boundsAssertionTolerance` throws |
| `setContent { }` | exactly once per test |
| `waitForIdle()` / `awaitIdle()` / `runOnIdle { }` | settle composition, measure, layout |
| `mainClock.advanceTimeBy(ms)`, `autoAdvance`, `advanceTimeByFrame()` | Compose time |
| `waitUntil { }`, `waitUntilExactlyOneExists(matcher)`, `waitUntilDoesNotExist(matcher)` | wall-clock polling |
| `performTextInput`, `performTextReplacement`, `performTextClearance`, `performImeAction` | text fields |
| `assertIsDisplayed`, `assertDoesNotExist`, `assertIsEnabled`, `assertIsNotEnabled`, `assertTextEquals` | assertions |
| `awaitPendingResourceStateLoads()` (`org.jetbrains.compose.resources`, CMP 1.13+, `@ExperimentalResourceApi`) | web only: wait for async resource loads, then `waitForIdle()`. A no-op on blocking platforms |
### Limits outside Android (iOS, desktop, web)
- Content renders off-screen into a 1024 x 768 px canvas at density 1, not in a `UIWindow`: no UIKit
view tree, safe-area insets, keyboard, VoiceOver or system Dynamic Type. Test those with
`kmp-maestro-e2e` or XCUITest.
- The window reads as 1024 dp wide, so a layout that branches on window size class takes its
expanded branch. Pass the size class into the content composable and test each branch.
- `DeviceConfigurationOverride.ForcedSize`, `FontScale`, `LayoutDirection` and `WindowSize` throw
`UnsupportedOperationException` on these targets (1.13.0 sources). Provide `LocalDensity`
(with `fontScale`) or `LocalLayoutDirection` through `CompositionLocalProvider` instead.
- `registerIdlingResource` returns `false` on iOS and web: wait with `waitUntil` instead.
- `Dispatchers.Main` work may never run in an iOS test binary: always `Dispatchers.setMain`.
## Verify
```bash
./gradlew :shared:iosSimulatorArm64Test --tests "com.example.app.notes.*" # macOS only
./gradlew :shared:jvmTest --tests "com.example.app.notes.*" # if there is a jvm() target
./gradlew :shared:assembleAndroidDeviceTest # compiles the device-test APK, no device needed
./gradlew :shared:connectedAndroidDeviceTest # device or emulator running (legacy: connectedAndroidTest)
grep -rn "import androidx.compose.ui.test.runComposeUiTest" shared/src/commonTest # empty on CMP 1.11+ unless the project chose v1
```
Report each line as **PASS**, **FAIL** (first failing test and its message) or **NOT RUN** with the
reason, for example "Android NOT RUN: no emulator; common UI tests cannot run as host tests". Never
report UI tests as passing when only one target ran. Run new tests three times in a row on iOS; a
test that fails once is flaky (`kmp-flaky-test-triage`).
## Common mistakes
| Mistake | Why it bites | Fix |
|---|---|---|
| Asserting a callback list or fake right after `performClick` | v2 queues work; the assertion runs before the click is processed | `waitForIdle()` (or `runOnIdle { }`) before reading non-Compose state |
| Porting v1 tests by changing only the import | v1 ran effects eagerly; v2 does not | add `waitForIdle()` / `mainClock.advanceTimeBy` where results come from coroutines |
| Expecting `waitForIdle()` to finish a `delay` | idleness ignores delayed coroutines | `mainClock.advanceTimeBy(ms)` |
| Block body `fun t() { runComposeUiTest { } }` or code after it | the `TestResult` is dropped; on web the test ends before it runs | `fun t() = runComposeUiTest { ... }` |
| Running common UI tests with `testAndroidHostTest` / IDE Android local config | not supported; nothing runs or the run fails | `connectedAndroidDeviceTest` (legacy: `connectedAndroidTest`) on a device |
| `withDeviceTest {}` without `sourceSetTreeName = "test"` | `androidDeviceTest` does not see `commonTest`; zero Android UI tests | `withDeviceTestBuilder { sourceSetTreeName = "test" }` |
| Locating by text | breaks on translation, truncation, Dynamic Type | constants from the shared `TestTags` object |
| No `Dispatchers.setMain` in a screen test | `viewModelScope` never runs on iOS; JVM throws "Module with the Main dispatcher is missing" | set an Unconfined or Standard test dispatcher |
| Sharing one scheduler between `runTestContext` and `effectContext` | rejected by the API contract | keep them separate; give only Main your own dispatcher |
| `DeviceConfigurationOverride` in a common test | throws on iOS, desktop and web | CompositionLocals or a parameter |
| Real repository, network or database in UI tests | slow, order-dependent, fails offline | hand-written fake in `commonTest` |
## Related skills
- `kmp-testing-patterns`: ViewModel and repository unit tests, fakes, dispatchers.
- `mobile-accessibility-test-ids`: the tag contract shared by UI tests, Maestro and XCUITest.
- `kmp-screenshot-testing`: golden images of the same composables.
- `kmp-maestro-e2e`: real-device flows across screens.
- `kmp-flaky-test-triage`: a UI test that fails only sometimes or only on one platform.
- `compose-multiplatform-screen` and `compose-design-system-component`: the shapes these tests target.
- `kmp-build-check`: both-platform build and test run before a PR.
- [Testing Compose Multiplatform UI](https://kotlinlang.org/docs/multiplatform/compose-test.html):
the official setup page.
- Google [testing-setup](https://github.com/android/skills/tree/main/testing/testing-setup): test
strategy for Android-only modules and host apps.
Files in this skill
- SKILL.md
- references/notes-test-examples.md
- references/setup-and-targets.md
Attribution
Related skills
View all in development →Comments
Loading comments…
Newsletter
Get the weekly list of safe new skills, and the ones we pulled.