Get started
Introduction
Installation
Your first app
Tutorials
Fission tutorials
Test an iOS app in the simulator and on a device
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 an iOS app in the simulator and on a device

Test a real task-completion flow with Rust assertions, provider checks, manual LiveTest commands and separate physical haptic checks.
iOS

What you will build

Choose the test layer which can detect each task-completion failure and keep its target-specific evidence explicit.
Assert the actual completion rule and controlled provider contract
Drive the simulator screen through semantic selectors and inspect its screenshot
Reserve physical haptic claims for a signed iPhone run
A test is useful because of the failure it can detect, not because it ran on an impressive-looking target. A pure Rust test can establish that a blank task does not overwrite an existing completion. It cannot establish that an iPhone produced a haptic response. Conversely, feeling a vibration tells us nothing about whether an invalid submission changed the app's data.
We will test the task-completion app from the haptics tutorial. The user enters a task they have finished; the app records it and requests optional feedback. The same app supplies a small domain rule, an asynchronous host operation and an observable user journey without inventing a test-only product.
Start from a new project (optional)

Create the project and add the target

Complete iOS setup and simulator setup first. The commands that launch Apple's tools run on macOS.
cargo install cargo-fission
fission init ios-test-an-ios-app-in-the-simulator-and-on-a-device
cd ios-test-an-ios-app-in-the-simulator-and-on-a-device
fission add-target ios --project-dir .
fission add-capability haptics --project-dir .
cargo add serde_yaml
Keep the generated src/main.rs. The normal src/lib.rs below installs the shared app for native and Web targets; the preview is not a separate implementation of the task.

Run the finished example

fission run --target ios --project-dir .

1. Give the tests a real state transition

The screen starts empty. Completion records a trimmed task, clears its draft and sets feedback pending before queuing any host work. A blank submission or a second submission whilst pending changes nothing. Extracting that small rule makes its invariant testable without constructing a window or pretending a provider ran.
The provider check below deliberately uses MemoryHapticHost and UnsupportedHapticHost inside #[cfg(test)]. It establishes their contract, not the effect dispatcher's integration or physical feedback. Normal launches and this browser preview still use their actual platform providers. The production callbacks bind unit actions and decode the actual host input.
{"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"}]}
{"id":"fission-tabs-1","index":0,"label":"src/app.rs","value":"src-app-rs"}
pub mod screen;
pub mod state;

pub use screen::TaskCompletionScreen;
pub use state::TaskState;
{"id":"fission-tabs-1","index":1,"label":"src/app/state.rs","value":"src-app-state-rs"}
use fission::prelude::*;

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum Feedback {
    #[default]
    Idle,
    Pending,
    Accepted,
    Unavailable,
    InvalidResult,
}

impl Feedback {
    pub fn message_key(&self) -> &'static str {
        match self {
            Self::Idle => "feedback.optional",
            Self::Pending => "feedback.pending",
            Self::Accepted => "feedback.accepted",
            Self::Unavailable => "feedback.unavailable",
            Self::InvalidResult => "feedback.invalid",
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TaskState {
    pub draft: String,
    pub completed: Option<String>,
    pub feedback: Feedback,
    pub locale: Locale,
}

impl Default for TaskState {
    fn default() -> Self {
        Self {
            draft: String::new(),
            completed: None,
            feedback: Feedback::Idle,
            locale: Locale::from("en-US"),
        }
    }
}

impl GlobalState for TaskState {}

pub fn record_completion(state: &mut TaskState) -> bool {
    if state.feedback == Feedback::Pending || state.draft.trim().is_empty() {
        return false;
    }
    state.completed = Some(state.draft.trim().to_owned());
    state.draft.clear();
    state.feedback = Feedback::Pending;
    true
}

pub fn complete_task(state: &mut TaskState, cx: &mut ReducerContext<TaskState>) {
    if !record_completion(state) {
        return;
    }

    let ok = cx
        .effects
        .bind(HapticAccepted, reduce_with!(on_haptic_accepted));
    let err = cx
        .effects
        .bind(HapticUnavailable, reduce_with!(on_haptic_unavailable));
    cx.effects
        .haptics()
        .notification(HapticNotificationRequest {
            kind: HapticNotificationKind::Success,
        })
        .on_ok(ok)
        .on_err(err);
}

#[fission_reducer(HapticAccepted)]
fn on_haptic_accepted(state: &mut TaskState, cx: &mut ReducerContext<TaskState>) {
    state.feedback = if cx.input.capability_ok(HAPTIC_NOTIFICATION).is_some() {
        Feedback::Accepted
    } else {
        Feedback::InvalidResult
    };
}

#[fission_reducer(HapticUnavailable)]
fn on_haptic_unavailable(state: &mut TaskState, cx: &mut ReducerContext<TaskState>) {
    state.feedback = if cx.input.capability_error(HAPTIC_NOTIFICATION).is_some() {
        Feedback::Unavailable
    } else {
        Feedback::InvalidResult
    };
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::*;

    #[test]
    fn completion_records_trimmed_input_before_feedback() {
        let mut state = TaskState::default();
        state.draft = "  Check the fire exit  ".into();
        assert!(record_completion(&mut state));
        assert_eq!(state.completed.as_deref(), Some("Check the fire exit"));
        assert!(state.draft.is_empty());
        assert_eq!(state.feedback, Feedback::Pending);
    }

    #[test]
    fn blank_and_busy_submissions_preserve_previous_completion() {
        let mut state = TaskState::default();
        state.completed = Some("Check the fire exit".into());
        state.draft = "  ".into();
        assert!(!record_completion(&mut state));
        state.feedback = Feedback::Pending;
        state.draft = "Check the loading bay".into();
        assert!(!record_completion(&mut state));
        assert_eq!(state.completed.as_deref(), Some("Check the fire exit"));
        assert_eq!(state.draft, "Check the loading bay");
    }

    #[test]
    fn test_providers_distinguish_acceptance_from_unavailability() {
        let memory = MemoryHapticHost::default();
        let request = HapticNotificationRequest {
            kind: HapticNotificationKind::Success,
        };
        assert!(memory.notification(request).is_ok());
        assert_eq!(memory.calls(), vec!["notification".to_owned()]);
        assert!(UnsupportedHapticHost
            .notification(HapticNotificationRequest {
                kind: HapticNotificationKind::Success,
            })
            .is_err());
    }
}
{"id":"fission-tabs-1","index":2,"label":"src/app/screen.rs","value":"src-app-screen-rs"}
use super::state::{complete_task, Feedback, TaskState};
use fission::prelude::*;

fission_component! {
    pub TaskCompletionScreen<TaskState> {}
    view(_screen, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
        let pending = state.feedback == Feedback::Pending;
    } => SafeArea(
        child: Scroll(
            child: Container(
                Column(gap: tokens.spacing.m, children: [
                    Text(cx.tr("task.title"))
                        .size(tokens.typography.heading2_size),
                    Text(cx.tr("task.explanation"))
                        .color(tokens.colors.text_secondary),
                    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"); },
                        ),
                    ]),
                    FormControl(
                        label: Some(cx.tr("task.label")),
                        required: true,
                        child: TextInput(
                            value: state.draft.clone(),
                            bind(on_input): to(state.draft),
                            placeholder: Some(TextContent::Key("task.placeholder".into())),
                            semantics_identifier: Some("task.draft".into()),
                        ),
                    ),
                    Button(
                        child: Text(cx.tr("task.complete")),
                        key: "complete-task",
                        disabled: pending || state.draft.trim().is_empty(),
                        on_press: reduce { complete_task(state, cx); },
                    )
                    .semantics_identifier("task.complete"),
                    if let Some(task) = &state.completed {
                        Text(cx.tr("task.completed").replace("{task}", task))
                    },
                    if pending {
                        Spinner(
                            motion: Some(SpinnerMotion::Default),
                            label: Some(cx.tr("feedback.pending")),
                        )
                    },
                    Text(cx.tr(state.feedback.message_key())),
                    Text(cx.tr("task.persistence"))
                        .color(tokens.colors.text_secondary),
                ]),
            )
            .padding_all(tokens.spacing.l)
            .bg(tokens.colors.surface),
        ),
    )
}
{"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 task translations");
        env.i18n.add_bundle(TranslationBundle {
            locale: Locale::from(locale),
            messages,
        });
    }
    env
}

pub fn sync_env(state: &crate::app::TaskState, 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;
mod i18n;

use app::{TaskCompletionScreen, TaskState};
use fission::prelude::*;

#[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
pub fn run_desktop() -> anyhow::Result<()> {
    DesktopApp::<TaskState, _>::new(TaskCompletionScreen)
        .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::<TaskState, _>::new(TaskCompletionScreen)
        .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::<TaskState, _>::new(TaskCompletionScreen)
        .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::<TaskState, _>::new(TaskCompletionScreen)
        .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::TaskState, _>::new(app::TaskCompletionScreen)
        .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"}
task.title: "Finish a task"
task.explanation: "Enter a task you have finished. Its completion stays visible even when haptic feedback is unavailable."
task.label: "Completed task"
task.placeholder: "For example, send the supplier invoice"
task.complete: "Mark complete"
task.completed: "Completed: {task}"
task.persistence: "Tasks are kept in memory for this session. This example does not save them."
language.english: "English"
language.spanish: "Español"
feedback.optional: "Haptic feedback is an optional confirmation."
feedback.pending: "Task completed. Waiting for optional haptic feedback…"
feedback.accepted: "Task completed. The host accepted the haptic request."
feedback.unavailable: "Task completed. Haptic feedback is unavailable on this host."
feedback.invalid: "Task completed. The host returned an unexpected feedback result."
{"id":"fission-tabs-1","index":7,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
task.title: "Finaliza una tarea"
task.explanation: "Escribe una tarea que hayas terminado. La confirmación permanece visible aunque la respuesta háptica no esté disponible."
task.label: "Tarea terminada"
task.placeholder: "Por ejemplo, enviar la factura al proveedor"
task.complete: "Marcar como terminada"
task.completed: "Terminada: {task}"
task.persistence: "Las tareas se conservan en memoria durante esta sesión. Este ejemplo no las guarda."
language.english: "Inglés"
language.spanish: "Español"
feedback.optional: "La respuesta háptica es una confirmación opcional."
feedback.pending: "Tarea terminada. Esperando la respuesta háptica opcional…"
feedback.accepted: "Tarea terminada. El host ha aceptado la solicitud háptica."
feedback.unavailable: "Tarea terminada. La respuesta háptica no está disponible en este host."
feedback.invalid: "Tarea terminada. El host ha devuelto un resultado inesperado."
{"id":"fission-tabs-1"}
Enter a completed task and submit it. The visible completion remains even when feedback is unavailable. Changing the interface language must not change the user's task.
Show the app preview
Hide the app preview

2. Drive the actual simulator screen

Run the narrow Rust tests, then the generated-host smoke check. These are separate checks: the former exercises our assertions; the latter checks that the generated simulator host can start.
cargo test --lib
fission doctor ios --project-dir .
fission test --target ios --project-dir .
FISSION_TEST_CONTROL_PORT=48762 fission run --target ios --project-dir .
The run script forwards the port into the simulator process. Use another terminal on the same Mac to issue these requests. LiveTest listens on loopback, and it controls the application, so enable it only for a deliberate test launch. Do not bake a test port into a distributed app.
curl --fail-with-body http://127.0.0.1:48762/health
curl --fail-with-body -H 'Content-Type: application/json' \
  --data '{"cmd":"GetTree"}' http://127.0.0.1:48762/cmd

curl --fail-with-body -H 'Content-Type: application/json' \
  --data '{"cmd":"FillText","query":{"selector":{"kind":"semantic_identifier","identifier":"task.draft"}},"text":"Check the fire exit"}' \
  http://127.0.0.1:48762/cmd

curl --fail-with-body -H 'Content-Type: application/json' \
  --data '{"cmd":"ActivateSelector","query":{"selector":{"kind":"semantic_identifier","identifier":"task.complete"}}}' \
  http://127.0.0.1:48762/cmd

curl --fail-with-body -H 'Content-Type: application/json' \
  --data '{"cmd":"WaitForText","text":"Completed: Check the fire exit","timeout_ms":5000}' \
  http://127.0.0.1:48762/cmd
Inspect each JSON response. A successful HTTP exchange can still contain a LiveTest Error or SelectorError; curl --fail-with-body does not turn those application-level failures into an assertion. The wait must return {"status":"Ok"}. Use the stable identifiers for controls so a translated label does not break selection. This particular text assertion intentionally targets the default English locale.
A screenshot gives different evidence again. Request CaptureScreenshot and save its base64 PNG on the client, rather than asking the simulator to write a path on your Mac. This command uses jq; install it separately if it is not already available.
mkdir -p .artifacts
curl --fail-with-body -H 'Content-Type: application/json' \
  --data '{"cmd":"CaptureScreenshot"}' http://127.0.0.1:48762/cmd \
  | jq -er 'if .status == "Screenshot" then .png_base64 else error("screenshot failed") end' \
  | base64 --decode > .artifacts/task-completed.png
Open the image. Check the task text, status, safe-area spacing and keyboard state; a file existing does not establish that the screen looks correct. Repeat with a long task and Spanish labels. Use the LiveTest reference when converting these manual requests into a repeatable client test.
A passing domain test, an accepted provider request, a successful selector operation and a correct screenshot establish different things. Record each result against the target where it was observed.
Show the app preview
Hide the app preview

3. Reserve physical-device checks for physical behaviour

Follow iPhone signing and installation to install this same app. fission run --target ios launches the simulator, not a phone. A release build or signed IPA is not proof that a user completed the journey.
On an iPhone, enter a task and mark it complete. Check that the text confirmation is sufficient with feedback suppressed, then judge the cue on supported hardware. An accepted haptic request does not guarantee that a person felt it. Test with VoiceOver, a larger text setting and a long translated label whilst the actual keyboard is open.
For a failure-path integration run, install an unsupported or controlled provider in an explicitly test-only launcher, then drive the same real button and completion reducer. Do not change the production screen to a row of “success” and “failure” buttons; that would bypass the dispatcher we need to test. The next capability-testing tutorial separates those provider-controlled runs from native qualification.
Keep the source revision, simulator/runtime or phone/iOS version, scenario, observed result and screenshot together. Report untested hardware separately instead of promoting a passing browser preview into an iOS result.