Get started
Introduction
Installation
Your first app
Tutorials
Fission tutorials
Test mobile capability flows without depending on hardware for every test
Core concepts
Components
State and effects
Protected routes
Server-side rendering
Styling
Testing
Deployment
Reference
API reference
Cookbook
Fission 0.16.0
Documentation version
Read the changelog →

Test mobile capability flows without depending on hardware for every test

Drive actual camera-permission reducers with test-only providers whilst preserving the user's caption through denial and unsupported results.
Android

What you will build

Inject controlled permission results at the provider boundary without replacing the production screen with simulated outcome buttons.
Keep memory providers inside an explicitly test-only launcher
Drive the normal request and bound completion reducers through LiveTest
Separate deterministic recovery tests from native prompt and hardware qualification
A permission failure should not cost someone the note they were writing. That is an application rule which we can test without a phone. Whether iOS displays the right permission prompt is a different question and still needs the native host.
We will use the real caption-and-permission screen from the privacy tutorial. A dedicated test launcher injects a controlled camera provider, then the normal button queues the normal effect and its actual completion updates the normal reducers. There are no “pretend success” buttons inside the product screen.

Create the shared project

Complete the Android setup and iOS setup guides before checking their native paths.
cargo install cargo-fission
fission init mobile-test-mobile-capability-flows-without-depending-on-hardware-for-every-test
cd mobile-test-mobile-capability-flows-without-depending-on-hardware-for-every-test
fission add-target android ios --project-dir .
fission add-capability camera --project-dir .
cargo add serde_yaml
Keep the generated src/main.rs. Its shared library installs the real platform provider by default. The separate examples/camera_test_host.rs is test infrastructure, not an alternate production entrypoint. Its crate import matches the project name above; change that import if you choose a different package name.

Run the finished example

fission run --target android --project-dir .

1. Keep production and controlled-provider launches distinct

The caption belongs to the screen's retained draft state. Permission state belongs to the app because another part of a larger workflow may observe it. Only an explicit button action requests access. Pending state disables a duplicate request but does not lock the draft.
The test host supplies either a memory permission result or an unsupported error. Its memory provider has no image data because this screen never calls capture; a permission grant must not be presented as an attached photograph.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/app.rs","value":"src-app-rs"},{"index":1,"label":"src/app/state.rs","value":"src-app-state-rs"},{"index":2,"label":"src/app/screen.rs","value":"src-app-screen-rs"},{"index":3,"label":"src/i18n.rs","value":"src-i18n-rs"},{"index":4,"label":"src/lib.rs","value":"src-lib-rs"},{"index":5,"label":"preview/lib.rs","value":"preview-lib-rs"},{"index":6,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"},{"index":7,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"},{"index":8,"label":"examples/camera_test_host.rs","value":"examples-camera-test-host-rs"}]}
{"id":"fission-tabs-1","index":0,"label":"src/app.rs","value":"src-app-rs"}
mod screen;
pub mod state;
pub use screen::PhotoAccessScreen;
pub use state::PhotoAccessState;
{"id":"fission-tabs-1","index":1,"label":"src/app/state.rs","value":"src-app-state-rs"}
use fission::prelude::*;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PhotoAccessState {
    pub locale: Locale,
    pub pending: bool,
    pub permission: Option<CameraPermission>,
    pub status_key: String,
    pub error: Option<String>,
}

impl Default for PhotoAccessState {
    fn default() -> Self {
        Self {
            locale: Locale::from("en-US"),
            pending: false,
            permission: None,
            status_key: "photo.ready".into(),
            error: None,
        }
    }
}
impl GlobalState for PhotoAccessState {}

pub fn request_access(state: &mut PhotoAccessState, cx: &mut ReducerContext<PhotoAccessState>) {
    if state.pending {
        return;
    }
    state.pending = true;
    state.error = None;
    state.status_key = "photo.pending".into();
    let ok = cx
        .effects
        .bind(PermissionReturned, reduce_with!(permission_returned));
    let err = cx
        .effects
        .bind(PermissionFailed, reduce_with!(permission_failed));
    cx.effects
        .camera()
        .request_permission(CameraPermissionRequest { reason: None })
        .on_ok(ok)
        .on_err(err);
}

#[fission_reducer(PermissionReturned)]
fn permission_returned(state: &mut PhotoAccessState, cx: &mut ReducerContext<PhotoAccessState>) {
    state.pending = false;
    state.permission = cx.input.capability_ok(REQUEST_CAMERA_PERMISSION);
    state.status_key = match state.permission {
        Some(CameraPermission::Granted) => "photo.granted",
        Some(CameraPermission::Denied) => "photo.denied",
        Some(CameraPermission::Restricted) => "photo.restricted",
        Some(CameraPermission::Unknown) => "photo.unknown",
        None => "photo.unexpected",
    }
    .into();
}

#[fission_reducer(PermissionFailed)]
fn permission_failed(state: &mut PhotoAccessState, cx: &mut ReducerContext<PhotoAccessState>) {
    state.pending = false;
    let error = cx.input.capability_error(REQUEST_CAMERA_PERMISSION);
    state.status_key = if error
        .as_ref()
        .is_some_and(|error| error.code == "unsupported")
    {
        "photo.unsupported"
    } else {
        "photo.failed"
    }
    .into();
    state.error = error
        .map(|error| format!("{}: {}", error.code, error.message))
        .or_else(|| {
            cx.input
                .capability_error_message(REQUEST_CAMERA_PERMISSION)
                .map(str::to_owned)
        });
}
{"id":"fission-tabs-1","index":2,"label":"src/app/screen.rs","value":"src-app-screen-rs"}
use super::state::{request_access, PhotoAccessState};
use fission::prelude::*;

fission_component! {
    pub PhotoAccessScreen<PhotoAccessState> {
        state { caption: String = String::new() }
    }
    view(form, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
    } => SafeArea(
        child: Scroll(
            child: Container(Column(gap: tokens.spacing.m, children: [
                Text(cx.tr("photo.heading")).size(tokens.typography.heading2_size),
                Text(cx.tr("photo.explanation")),
                Row(gap: tokens.spacing.s, children: [
                    Button(
                        child: Text(cx.tr("language.english")), key: "english",
                        on_press: reduce { state.locale = Locale::from("en-US"); },
                    ),
                    Button(
                        child: Text(cx.tr("language.spanish")), key: "spanish",
                        on_press: reduce { state.locale = Locale::from("es-ES"); },
                    ),
                ]),
                TextInput(
                    value: form.caption.clone(), bind(on_input): to(form.caption),
                    label: Some(TextContent::Key("photo.caption".into())),
                    helper_text: Some(TextContent::Key("photo.caption_help".into())),
                    multiline: true, keyboard_type: TextInputType::Multiline,
                    semantics_identifier: Some("photo.caption".into()),
                ),
                Button(
                    child: Text(cx.tr("photo.request")), key: "request-camera-access",
                    disabled: state.pending,
                    on_press: reduce { request_access(state, cx); },
                ).semantics_identifier("photo.request"),
                if state.pending {
                    Spinner(motion: Some(SpinnerMotion::Default), label: Some(cx.tr("photo.pending")))
                },
                Text(cx.tr("photo.last_response")).weight(tokens.typography.font_weight_semibold),
                Text(cx.tr(&state.status_key)),
                if let Some(error) = &state.error { Code(text: error.clone()) },
                Text(cx.tr("photo.scope")).color(tokens.colors.text_secondary),
            ]))
            .padding_all(tokens.spacing.l),
        ),
    )
}
{"id":"fission-tabs-1","index":3,"label":"src/i18n.rs","value":"src-i18n-rs"}
use fission::i18n::{Locale, TranslationBundle};
use fission::prelude::*;
use std::collections::HashMap;

pub fn create_env() -> Env {
    let mut env = Env::default();
    env.locale = Locale::from("en-US");
    for (locale, source) in [
        ("en-US", include_str!("../i18n/en-US.yaml")),
        ("es-ES", include_str!("../i18n/es-ES.yaml")),
    ] {
        let messages: HashMap<String, String> =
            serde_yaml::from_str(source).expect("valid photo access translations");
        env.i18n.add_bundle(TranslationBundle {
            locale: Locale::from(locale),
            messages,
        });
    }
    env
}

pub fn sync_env(state: &crate::app::PhotoAccessState, env: &mut Env) {
    env.locale = state.locale.clone();
}
{"id":"fission-tabs-1","index":4,"label":"src/lib.rs","value":"src-lib-rs"}
pub mod app;
pub mod i18n;

use app::{PhotoAccessScreen, PhotoAccessState};
use fission::prelude::*;

#[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
pub fn run_desktop() -> anyhow::Result<()> {
    DesktopApp::<PhotoAccessState, _>::new(PhotoAccessScreen)
        .with_env(i18n::create_env())
        .with_sync_env(i18n::sync_env)
        .run()
}

#[cfg(any(target_os = "android", target_os = "ios"))]
pub fn run_mobile() -> anyhow::Result<()> {
    MobileApp::<PhotoAccessState, _>::new(PhotoAccessScreen)
        .with_env(i18n::create_env())
        .with_sync_env(i18n::sync_env)
        .run()
}

#[cfg(target_os = "android")]
#[no_mangle]
fn android_main(app_handle: AndroidApp) {
    let _ = MobileApp::<PhotoAccessState, _>::new(PhotoAccessScreen)
        .with_env(i18n::create_env())
        .with_sync_env(i18n::sync_env)
        .run_with_android_app(app_handle);
}

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn run_web() -> Result<(), wasm_bindgen::JsValue> {
    console_error_panic_hook::set_once();
    WebApp::<PhotoAccessState, _>::new(PhotoAccessScreen)
        .with_env(i18n::create_env())
        .with_sync_env(i18n::sync_env)
        .run()
        .map_err(|error| wasm_bindgen::JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":5,"label":"preview/lib.rs","value":"preview-lib-rs"}
mod app;
mod i18n;

use fission::prelude::*;
use wasm_bindgen::prelude::*;

#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
    console_error_panic_hook::set_once();
    WebApp::<app::PhotoAccessState, _>::new(app::PhotoAccessScreen)
        .with_env(i18n::create_env())
        .with_sync_env(i18n::sync_env)
        .mount("#fission-web-mount")
        .run()
        .map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":6,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"}
photo.heading: "Prepare a photo attachment"
photo.explanation: "A photo can add context to your note. Request camera access when you choose that feature; you can keep writing without it."
photo.caption: "What would the photo show?"
photo.caption_help: "This draft remains editable if camera access is unavailable."
photo.request: "Request camera access"
photo.last_response: "Last camera permission response"
photo.ready: "Camera access has not been requested."
photo.pending: "Waiting for the camera permission response…"
photo.granted: "The host reported camera access granted. No photograph has been taken."
photo.denied: "Access was denied. You can review this app's camera permission in iOS Settings or continue writing."
photo.restricted: "Access is restricted. It may require a device-management or parental-control change; you can continue writing."
photo.unknown: "The permission state remains unknown. No photograph has been taken."
photo.unexpected: "The host returned no usable permission result."
photo.unsupported: "This host does not support the camera permission operation."
photo.failed: "The permission operation failed. Your draft is unchanged."
photo.scope: "This example checks permission only. It does not capture, attach, upload or save a photo or note."
language.english: "English"
language.spanish: "Español"
{"id":"fission-tabs-1","index":7,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
photo.heading: "Preparar una foto adjunta"
photo.explanation: "Una foto puede dar contexto a tu nota. Solicita acceso a la cámara al elegir esa función; puedes seguir escribiendo sin ella."
photo.caption: "¿Qué mostraría la foto?"
photo.caption_help: "Este borrador sigue siendo editable si la cámara no está disponible."
photo.request: "Solicitar acceso a la cámara"
photo.last_response: "Última respuesta de permiso de cámara"
photo.ready: "No se ha solicitado acceso a la cámara."
photo.pending: "Esperando la respuesta de permiso de cámara…"
photo.granted: "El host indicó que se concedió acceso. No se ha tomado ninguna foto."
photo.denied: "Se denegó el acceso. Puedes revisar el permiso de cámara de esta app en Ajustes o seguir escribiendo."
photo.restricted: "El acceso está restringido. Puede requerir un cambio de gestión del dispositivo o control parental; puedes seguir escribiendo."
photo.unknown: "El permiso sigue siendo desconocido. No se ha tomado ninguna foto."
photo.unexpected: "El host no devolvió un resultado de permiso utilizable."
photo.unsupported: "Este host no admite la operación de permiso de cámara."
photo.failed: "La operación de permiso falló. Tu borrador no ha cambiado."
photo.scope: "Este ejemplo solo comprueba el permiso. No captura, adjunta, sube ni guarda fotos o notas."
language.english: "Inglés"
language.spanish: "Español"
{"id":"fission-tabs-1","index":8,"label":"examples/camera_test_host.rs","value":"examples-camera-test-host-rs"}
use fission::prelude::*;
use mobile_test_mobile_capability_flows_without_depending_on_hardware_for_every_test::{
    app::{PhotoAccessScreen, PhotoAccessState},
    i18n,
};

fn memory_camera(permission: CameraPermission) -> MemoryCameraHost {
    // This test requests permission only; it never captures these empty bytes.
    MemoryCameraHost::new(
        CameraAvailability {
            permission,
            devices: Vec::new(),
        },
        Vec::new(),
        "image/png",
        0,
        0,
        None,
    )
}

fn main() -> anyhow::Result<()> {
    let outcome = std::env::args()
        .nth(1)
        .ok_or_else(|| anyhow::anyhow!("expected granted, denied or unsupported"))?;
    let app = DesktopApp::<PhotoAccessState, _>::new(PhotoAccessScreen)
        .with_env(i18n::create_env())
        .with_sync_env(i18n::sync_env);
    match outcome.as_str() {
        "granted" => app
            .with_camera_host(memory_camera(CameraPermission::Granted))
            .run(),
        "denied" => app
            .with_camera_host(memory_camera(CameraPermission::Denied))
            .run(),
        "unsupported" => app.with_camera_host(UnsupportedCameraHost).run(),
        _ => Err(anyhow::anyhow!("unknown test outcome")),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn controlled_providers_return_distinct_permission_results() {
        for permission in [CameraPermission::Granted, CameraPermission::Denied] {
            let actual = memory_camera(permission)
                .request_permission(CameraPermissionRequest { reason: None });
            assert_eq!(actual, Ok(permission));
        }
        let error = UnsupportedCameraHost
            .request_permission(CameraPermissionRequest { reason: None })
            .expect_err("unsupported must not become a grant");
        assert_eq!(error.code, "unsupported");
    }
}
{"id":"fission-tabs-1"}
This preview uses the browser's actual camera-permission provider, not the test launcher. Write a caption, request access and inspect the result. The draft must remain editable regardless of the response.
Show the app preview
Hide the app preview

2. Exercise the same effect path with controlled outcomes

Run these on a desktop with a graphical session. The example launcher opens the same Compose screen and installs a controlled host only for that process. Run each scenario separately, close its window, then launch the next.
cargo test --example camera_test_host
FISSION_TEST_CONTROL_PORT=48763 cargo run --example camera_test_host -- granted
FISSION_TEST_CONTROL_PORT=48763 cargo run --example camera_test_host -- denied
FISSION_TEST_CONTROL_PORT=48763 cargo run --example camera_test_host -- unsupported
The first command asserts the providers' distinct contract results. The launched app tests a broader path: a UI action requests a capability, the registry dispatches it to the injected host, and bound unit completion actions decode the result from cx.input. Use these requests whilst one scenario is open:
curl --fail-with-body -H 'Content-Type: application/json' \
  --data '{"cmd":"FillText","query":{"selector":{"kind":"semantic_identifier","identifier":"photo.caption"}},"text":"The parcel seal is damaged"}' \
  http://127.0.0.1:48763/cmd
curl --fail-with-body -H 'Content-Type: application/json' \
  --data '{"cmd":"ActivateSelector","query":{"selector":{"kind":"semantic_identifier","identifier":"photo.request"}}}' \
  http://127.0.0.1:48763/cmd
curl --fail-with-body -H 'Content-Type: application/json' \
  --data '{"cmd":"WaitForIdle","timeout_ms":5000,"ignore_repeating_motion":false}' \
  http://127.0.0.1:48763/cmd
curl --fail-with-body -H 'Content-Type: application/json' \
  --data '{"cmd":"GetTree"}' http://127.0.0.1:48763/cmd
Check the JSON application status, not only HTTP success. An Error or SelectorError is a failed command. With the English bundle selected, the screen must show the corresponding granted, denied or unsupported message from the checked-in translations. The caption's semantic value must still equal the text you entered, the request button must be enabled again, and the pending spinner must be gone.
Repeat the request and switch language. Inspect a screenshot as well as the semantic tree; both tell us something which a provider unit test cannot. The simulator-testing tutorial shows screenshot retrieval and the exact response format.
A granted memory response does not mean an actual camera was opened. A denied result here does not mean that iOS displayed a permission sheet. These runs establish the application's recovery behaviour, not the operating system's implementation.
The test executable may simulate outcomes because that is its declared purpose. Neither the normal native launcher nor the embedded preview silently installs that simulation.
Show the app preview
Hide the app preview

3. Check the remaining native boundary

Run the normal app, without the example launcher:
fission doctor android --project-dir .
fission run --target android --project-dir .
fission test --target android --project-dir .
fission doctor ios --project-dir .
fission run --target ios --project-dir .
fission test --target ios --project-dir .
The Android path requires the SDK, NDK and configured emulator from the setup guide. The iOS path runs on macOS with Xcode and an installed simulator runtime. Neither smoke test proves camera hardware, native purpose text or recovery after a real Settings change.
Use a physical Android phone and a physical iPhone for those checks. Verify the purpose description, grant, denial, restriction where applicable, returning from Settings and editing the caption whilst the response is pending. Do not repeatedly reset someone's permissions as a production recovery strategy.
Keep controlled-provider, simulator and phone results separate in the test record. A failing shared-state assertion should be reproducible without hardware; a native prompt defect needs evidence from the corresponding native host.