Skip to content
Back to skills

Kmp Screenshot Testing

ASecurity

Use when adding, recording or fixing screenshot (snapshot, golden image) tests in a Kotlin Multiplatform or Compose Multiplatform app - Roborazzi, recordRoborazzi or verifyRoborazzi tasks, captureRoboImage, Compose Preview Screenshot Testing (@PreviewTest, updateDebugScreenshotTest), Paparazzi, swift-snapshot-testing for SwiftUI screens, golden PNGs that differ between macOS and Linux CI, flaky pixel diffs from fonts, animations or time, dark mode and font scale variants, or screenshot diffs ...

  • 17 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 4, 2026
developmentgoswiftkotlinbashnodetestinggitapidatabasedocumentation

Works with

  • cursor
  • cli
  • api

Security analysis

A100/100

Pro scans all 3 files and shows the line behind each finding

Scanned December 4, 2026

npx -y skills add Kushpawan/kmp-mobile-skills --skill kmp-screenshot-testing --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Kmp Screenshot Testing?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Kmp Screenshot Testing
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/kushpawan-kmp-screenshot-testing/badge)](https://www.skillsdirectory.com/skills/kushpawan-kmp-screenshot-testing)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: kmp-screenshot-testing
description: Use when adding, recording or fixing screenshot (snapshot, golden image) tests in a Kotlin Multiplatform or Compose Multiplatform app - Roborazzi, recordRoborazzi or verifyRoborazzi tasks, captureRoboImage, Compose Preview Screenshot Testing (@PreviewTest, updateDebugScreenshotTest), Paparazzi, swift-snapshot-testing for SwiftUI screens, golden PNGs that differ between macOS and Linux CI, flaky pixel diffs from fonts, animations or time, dark mode and font scale variants, or screenshot diffs to upload from CI.
license: Apache-2.0
compatibility: Kotlin Multiplatform Gradle project with Compose Multiplatform or Jetpack Compose UI. Android capture runs on the JVM with Robolectric. iOS capture and SwiftUI snapshots need macOS with Xcode and an iOS simulator runtime.
metadata:
  category: testing
  platforms: android, ios
---

# KMP screenshot testing

A screenshot test renders one UI state, saves it as a reference image (a golden), and fails when a
later render differs. It catches visual regressions that assertions miss. It is only useful when
renders are deterministic, goldens are recorded in one known environment, and a failing diff is
reviewed instead of silenced.

## When to use

- Adding screenshot tests to a KMP or CMP module, or to the SwiftUI screens of the iOS host app.
- Recording, re-recording or reviewing goldens; a `verify` task failing after a UI change.
- Goldens that pass on one machine and fail on another (macOS vs Linux, Apple silicon vs x86).
- Adding dark mode, font scale or screen-size variants; wiring screenshot checks into CI.
- Choosing between Roborazzi, Compose Preview Screenshot Testing, Paparazzi and swift-snapshot-testing.

## When not to use

- Behaviour tests of Compose UI (clicks, text, navigation) without images: use
  `compose-multiplatform-ui-testing`.
- End-to-end flows on a running app, including Maestro `takeScreenshot` / `assertScreenshot`: use
  `kmp-maestro-e2e`.
- Unit tests of ViewModels and repositories: use `kmp-testing-patterns`.
- Stable `testTag` and `accessibilityIdentifier` locators: use `mobile-accessibility-test-ids`.
- A screenshot test that passes and fails without code changes, after the determinism steps below:
  use `kmp-flaky-test-triage`.

## Step 0 - Read the project first

Detect existing screenshot tooling and follow it. Recommend Roborazzi only when there is none.

```bash
grep -rnE "roborazzi|paparazzi|compose\.screenshot|screenshotTests|enableScreenshotTest|dropshots|karumi" \
  --include=*.kts --include=*.toml --include=*.properties .
grep -rln "SnapshotTesting\|assertSnapshot" --include=*.swift --include=Package.resolved .
find . -type d \( -name screenshots -o -name reference -o -name __Snapshots__ \) -not -path "*/build/*"
```

| Find out | Where to look | Follow it |
|---|---|---|
| Tool in use | the greps above | keep it; do not add a second screenshot tool for the same UI |
| Where goldens live | `roborazzi { outputDir }`, `src/screenshotTest*/reference`, `__Snapshots__/`, `.gitattributes` (LFS) | add new goldens next to the existing ones |
| Who records goldens | CI workflow, `Makefile`, `CONTRIBUTING.md` | record the same way (often a CI job), never on a different OS |
| Android test source set | `androidHostTest` (KMP library plugin), `androidUnitTest` / `test` (`com.android.library`) | put Android screenshot tests there |
| Test naming, theme, fixtures | existing `*ScreenshotTest*`, the app theme composable, `*Fixtures*` | reuse the project theme and fake data |
| Thresholds | `changeThreshold`, `maxPercentDifference`, `precision` | keep existing values; never raise one to pass a test |
| Versions | `gradle/libs.versions.toml`, Kotlin, AGP, Compose Multiplatform | add new libraries to the catalog only |

## Workflow

1. **Pick the tool.** Use the table; one tool per UI layer.

   | Situation | Tool | Status (Dec 2026) |
   |---|---|---|
   | Project already uses one | that tool | - |
   | Shared Compose Multiplatform UI, greenfield | Roborazzi | Android (Robolectric) stable; iOS and Desktop experimental |
   | Android-only module, team drives tests from `@Preview` | Compose Preview Screenshot Testing | alpha; no non-Android KMP targets |
   | Android module already on Paparazzi | Paparazzi | 1.3.5 stable, 2.0 still alpha |
   | Native SwiftUI screens in the iOS host app | swift-snapshot-testing | stable, MIT |

   Setup for the three alternatives is in [references/alternatives.md](references/alternatives.md).
   *Done when* one tool is chosen per UI layer and the reason is stated.

2. **Choose what to capture.** Screenshot the stateless content composable
   (`NotesListContent(state, onAction)`), not the ViewModel-bound screen: no Koin, no database, no
   network. Capture the states a user sees: notes list, `empty_state`, editor with text, error.
   Add variants only where they change layout: dark theme, `fontScale = 1.5f`, a narrow width.
   A capture of one component (`note_row_1`) is cheaper to review than a whole screen.

3. **Make every render deterministic.** Put one frame composable and fixed data in `commonTest`,
   so Android and iOS tests render identical inputs:

   ```kotlin
   // shared/src/commonTest/kotlin/com/example/app/notes/ScreenshotFrame.kt
   @Composable
   fun ScreenshotFrame(darkTheme: Boolean = false, fontScale: Float = 1f, content: @Composable () -> Unit) {
       val density = LocalDensity.current
       // Font scale and theme are explicit, so no test depends on device or simulator settings.
       CompositionLocalProvider(LocalDensity provides Density(density.density, fontScale)) {
           NotesTheme(darkTheme = darkTheme) {
               Surface(Modifier.size(width = 360.dp, height = 640.dp)) { content() }
           }
       }
   }

   object NotesFixtures {
       // Fixed ids, text and a pre-formatted date: no Clock.System.now(), no random UUIDs.
       val notes = listOf(
           Note(id = "1", title = "Groceries", body = "Milk, eggs, bread", updatedLabel = "2 Dec 2026"),
           Note(id = "2", title = "Trip plan", body = "Book the train", updatedLabel = "1 Dec 2026"),
       )
   }
   ```

   Also: bundle fonts as Compose resources instead of system fonts; pause the test clock
   (`mainClock.autoAdvance = false`) before capturing progress indicators or animations; do not
   focus text fields (the cursor blinks); replace remote images with a fake image loader or a
   placeholder; pin the locale and time zone. Details in
   [references/goldens-and-ci.md](references/goldens-and-ci.md#determinism-checklist).

4. **Set up Roborazzi for Android.** Catalog first:

   ```toml
   [versions]
   roborazzi = "1.81.0"
   robolectric = "4.18.1"
   androidx-compose-ui-test = "1.13.0"   # the Jetpack Compose version your CMP release maps to
   junit = "4.13.2"

   [libraries]
   roborazzi = { module = "io.github.takahirom.roborazzi:roborazzi", version.ref = "roborazzi" }
   roborazzi-compose = { module = "io.github.takahirom.roborazzi:roborazzi-compose", version.ref = "roborazzi" }
   roborazzi-compose-ios = { module = "io.github.takahirom.roborazzi:roborazzi-compose-ios", version.ref = "roborazzi" }
   robolectric = { module = "org.robolectric:robolectric", version.ref = "robolectric" }
   androidx-compose-ui-test-junit4 = { module = "androidx.compose.ui:ui-test-junit4", version.ref = "androidx-compose-ui-test" }
   androidx-compose-ui-test-manifest = { module = "androidx.compose.ui:ui-test-manifest", version.ref = "androidx-compose-ui-test" }
   junit = { module = "junit:junit", version.ref = "junit" }

   [plugins]
   roborazzi = { id = "io.github.takahirom.roborazzi", version.ref = "roborazzi" }
   ```

   Module on the `com.android.kotlin.multiplatform.library` plugin (AGP 9). Host tests are off until
   `withHostTest {}` opts in, and Roborazzi warns when `isIncludeAndroidResources` is not `true`:

   ```kotlin
   // shared/build.gradle.kts
   plugins {
       // ... kotlinMultiplatform, androidKotlinMultiplatformLibrary, composeMultiplatform, composeCompiler
       alias(libs.plugins.roborazzi)
   }
   kotlin {
       android {                                   // named androidLibrary {} before AGP 8.12
           withHostTest { isIncludeAndroidResources = true }
       }
       sourceSets {
           getByName("androidHostTest").dependencies {
               implementation(libs.roborazzi)
               implementation(libs.roborazzi.compose)
               implementation(libs.robolectric)
               implementation(libs.androidx.compose.ui.test.junit4)
               implementation(libs.androidx.compose.ui.test.manifest)   // provides the test activity
               implementation(libs.junit)
           }
       }
   }
   roborazzi {
       outputDir.set(file("src/screenshots"))       // default build/outputs/roborazzi is not committed
   }
   tasks.withType<Test>().configureEach {
       systemProperty("robolectric.pixelCopyRenderMode", "hardware")   // recommended by Roborazzi
   }
   ```

   On `com.android.library`, use `androidUnitTest` and `android { testOptions { unitTests {
   isIncludeAndroidResources = true } } }` instead.

5. **Write the Android test.** Robolectric with native graphics is required for real pixels:

   ```kotlin
   // shared/src/androidHostTest/kotlin/com/example/app/notes/NotesListScreenshotTest.kt
   @RunWith(RobolectricTestRunner::class)
   @GraphicsMode(GraphicsMode.Mode.NATIVE)
   @Config(sdk = [33])
   class NotesListScreenshotTest {
       @get:Rule val composeTestRule = createComposeRule()

       @Test
       fun should_matchGolden_when_listHasNotesInDarkTheme() {
           composeTestRule.setContent {
               ScreenshotFrame(darkTheme = true) {
                   NotesListContent(state = NotesListState(notes = NotesFixtures.notes), onAction = {})
               }
           }
           composeTestRule.onNodeWithTag("notes_list").assertIsDisplayed()   // fail fast on a blank render
           composeTestRule.onRoot().captureRoboImage()   // com.github.takahirom.roborazzi.captureRoboImage
       }
   }
   ```

   Without a path, the file name comes from the test class and method. *Done when*
   `./gradlew :shared:recordRoborazziAndroidHostTest` writes PNGs under `shared/src/screenshots`.

6. **Add iOS captures (experimental).** Add `roborazzi-compose-ios` and the Compose Multiplatform
   `ui-test` artifact to `iosTest` (the Roborazzi docs use `appleTest`). iOS has no automatic naming:
   pass `filePath` on every capture; a relative path resolves against the Roborazzi output directory.
   Output is PNG only.

   ```kotlin
   // shared/src/iosTest/kotlin/com/example/app/notes/NotesListIosScreenshotTest.kt
   import androidx.compose.ui.test.v2.runComposeUiTest
   import io.github.takahirom.roborazzi.captureRoboImage   // iOS package differs from Android's

   class NotesListIosScreenshotTest {
       @OptIn(ExperimentalTestApi::class, ExperimentalRoborazziApi::class)
       @Test
       fun should_matchGolden_when_listIsEmpty() = runComposeUiTest {
           setContent { ScreenshotFrame { NotesListContent(state = NotesListState(notes = emptyList()), onAction = {}) } }
           onNodeWithTag("empty_state").assertIsDisplayed()
           onRoot().captureRoboImage(this, filePath = "ios/notes_list_empty.png")
       }
   }
   ```

   This works with the v2 `runComposeUiTest` on Roborazzi 1.81.0, Compose Multiplatform 1.13.0 and
   Kotlin 2.5.0 (checked on `iosSimulatorArm64`, December 2026). iOS goldens never match Android goldens (different font rasterisers), so keep them in their own
   folder. *Done when* `recordRoborazziIosSimulatorArm64` writes `src/screenshots/ios/*.png`.

7. **Record goldens in one environment, then review them.** Record on the same OS, architecture,
   JDK and (for iOS) Xcode and simulator runtime that CI verifies on, usually by a CI job. Open every
   new PNG before committing: a golden of a blank screen, a crash dialog or a loading spinner is a
   bug, not a baseline. Commit goldens to git, or Git LFS when they grow large. Strategies in
   [references/goldens-and-ci.md](references/goldens-and-ci.md#where-goldens-live).

8. **Verify in CI and upload the diffs.** Run the verify task on every pull request and upload
   `build/outputs/roborazzi`, `build/reports/roborazzi` and `build/test-results/roborazzi` with
   `if: always()`, so a reviewer sees the `_compare.png` without rerunning. Workflow in
   [references/goldens-and-ci.md](references/goldens-and-ci.md#ci-workflow).

9. **Handle a failing diff.** Open the compare image. If the change is intended, re-record on the
   recording environment and commit the new golden in the same pull request, so the reviewer sees
   the image change. If not intended, fix the code. Never raise a threshold, delete a golden or
   skip the test to turn the build green.

## Quick reference

| Goal | Roborazzi task (KMP library plugin module) | Notes |
|---|---|---|
| Record Android goldens | `:shared:recordRoborazziAndroidHostTest` | `com.android.library` module: `recordRoborazziDebug` |
| Fail on any diff | `:shared:verifyRoborazziAndroidHostTest` | same name pattern; confirm with `./gradlew :shared:tasks --all \| grep -i roborazzi` |
| Write diff images, never fail | `:shared:compareRoborazziAndroidHostTest` | writes `*_compare.png` and JSON results |
| Verify, then re-record what changed | `verifyAndRecordRoborazzi<Variant>` | documented for Android variants; check the task list for KMP |
| iOS record / compare / verify | `recordRoborazziIosSimulatorArm64`, `compareRoborazziIosSimulatorArm64`, `verifyRoborazziIosSimulatorArm64` | macOS only, experimental |
| Same, through the plain test task | `-Proborazzi.test.record=true`, `.compare=true`, `.verify=true` | also settable in the root `gradle.properties` |

| Variant | Cross-platform (common code) | Android only (Robolectric) |
|---|---|---|
| Dark theme | `NotesTheme(darkTheme = true)` | `@Config(qualifiers = "+night")` |
| Font scale | `LocalDensity provides Density(density, fontScale = 1.5f)` | - |
| Screen size | fixed `Modifier.size(...)` in the frame | `@Config(qualifiers = RobolectricDeviceQualifiers.Pixel5)` |
| Locale | pass a fixed locale or pre-formatted strings | `@Config(qualifiers = "+ja")` |

| Option | Where | Use |
|---|---|---|
| `RoborazziOptions.CompareOptions(changeThreshold = 0.01F)` | per capture or rule | allowed fraction of changed pixels; justify any value above 0 |
| `SimpleImageComparator(maxDistance, vShift, hShift)` | `CompareOptions(imageComparator = ...)` | anti-aliasing noise on Android |
| `roborazzi.record.filePathStrategy=relativePathFromRoborazziContextOutputDirectory` | root `gradle.properties` | explicit Android paths resolve against `outputDir`, like iOS |
| `separateOutputDirs.set(true)` | `roborazzi { }` | one directory per task; stops races when several record tasks run in one build. Moves goldens: re-record after enabling. |

## Verify

```bash
./gradlew :shared:verifyRoborazziAndroidHostTest           # Android goldens, any OS with a JDK
./gradlew :shared:verifyRoborazziIosSimulatorArm64         # macOS with Xcode only
git status --short shared/src/screenshots                  # after a record: only intended goldens changed
```

Report each check as **PASS** (exit 0, no diffs), **FAIL** (name the failing capture and attach or
point to its `_compare.png`) or **NOT RUN** with the reason: for example "iOS verify NOT RUN: no
Xcode on this machine" or "goldens recorded on macOS, CI records on Linux: verify result not
meaningful". Never call a golden correct without opening the image. Never report "screenshot tests
pass" after a `record` run: recording always succeeds.

## Common mistakes

| Mistake | Why it bites | Fix |
|---|---|---|
| Goldens recorded on a Mac, verified on Linux CI | Font rasterising and anti-aliasing differ per OS; every test fails | Record and verify in the same environment, usually CI |
| Raising `changeThreshold` until the build passes | Hides real regressions; benchmarks treat it as cheating | Find the noise source; keep thresholds small and justified |
| Capturing the full device screen | Status bar clock and battery change every run | Capture the composable or `onRoot()` of the test content |
| Screenshotting the ViewModel-bound screen | Koin, database and network make renders vary or crash | Screenshot the stateless content composable with fixtures |
| `Clock.System.now()`, random ids or relative dates in UI | Golden changes every day or every run | Inject a clock; use fixed fixtures |
| Missing `@GraphicsMode(GraphicsMode.Mode.NATIVE)` | Robolectric renders nothing useful | Annotate every screenshot test class |
| No `withHostTest {}` on the KMP library plugin | `androidHostTest` is not compiled and no record task exists | `kotlin { android { withHostTest { isIncludeAndroidResources = true } } }` |
| Goldens left in `build/outputs/roborazzi` | `build/` is ignored; CI has nothing to compare | Set `roborazzi { outputDir }` under `src/`, or restore goldens from a CI artifact |
| iOS capture without `filePath` | Does not compile: iOS has no automatic naming | Pass `filePath = "ios/<name>.png"` |
| Android import used in `iosTest` | Packages differ (`com.github...` vs `io.github...`) | Import `io.github.takahirom.roborazzi.captureRoboImage` on iOS |
| Capturing a focused text field or a running spinner | Cursor blink and animation frames differ per run | Do not focus; set `mainClock.autoAdvance = false` |
| Re-recording without opening the images | A broken UI becomes the new baseline | Review every changed PNG in the pull request |
| Running record for Android and iOS in one Gradle call on Gradle 9 | Shared output directory races (`Cannot access input property 'roborazziImageInput'`) | One record task per invocation, or `separateOutputDirs` |

## Related skills

- `compose-multiplatform-ui-testing`: behaviour tests with `runComposeUiTest`, finders and actions.
- `kmp-maestro-e2e`: end-to-end flows and device-level screenshots on emulators and simulators.
- `mobile-accessibility-test-ids`: the `testTag`s these tests wait on before capturing.
- `kmp-testing-patterns`: fakes and fixtures for the state you render.
- `kmp-ci-github-actions`: runners, caching and artifacts for the CI job.
- `kmp-flaky-test-triage`: a screenshot test that still fails intermittently.
- `compose-design-system-component`: component galleries are good screenshot targets.
- [Roborazzi documentation](https://takahirom.github.io/roborazzi/) and its
  [multiplatform page](https://takahirom.github.io/roborazzi/compose-multiplatform.html).
- [android/skills `testing-setup`](https://github.com/android/skills): Google's Android-only testing
  skill, covers Compose Preview Screenshot Testing.

Files in this skill

  • SKILL.md18.3 KB
  • references/alternatives.md8.2 KB
  • references/goldens-and-ci.md9.3 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.