# Testing

> Canonical URL: https://docs.mountaya.com/en/sdks/dart/testing/
> Last updated: 2026-11-27
> Rules for agents: https://docs.mountaya.com/llms.txt#rules-for-agents

Test Dart and Flutter code that uses Mountaya: answer requests with MockClient, drive time with fake_async, script the map and navigation, and build errors.

Every part of the SDK runs in a test with no network and no device. The client takes your HTTP client and reads a clock a zone overrides. The map and navigation have scripted twins.

## Test code that calls the API

Every request leaves through `package:http`'s `Client`, so a test answers it with `MockClient`:

```dart
import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:mountaya_client/mountaya_client.dart';
import 'package:test/test.dart';

void main() {
  test('reads the activities', () async {
    final mountaya = Mountaya(
      credential: .publishable(key: 'pk_your_publishable_key'),
      httpClient: MockClient(
        (request) async => http.Response(
          jsonEncode({'data': <Object?>[]}),
          200,
          headers: {'content-type': 'application/json'},
        ),
      ),
    );
    final activities = await mountaya.studio.activities.getActivities();
    expect(activities.data, isEmpty);
    await mountaya.close();
  });
}
```

Add `http` to your test dependencies. A client handed `httpClient:` leaves it open on `close()`.

- `httpClient:` takes any `package:http` `Client`: `MockClient` for a test, `MockClient.streaming` for an event stream, and in an app `CupertinoClient` on iOS or `CronetClient` on Android for the operating system's stack. Every guarantee the client makes is set on each request, so it holds under any of them. A platform client may keep cookies of its own; configure it to keep none.
- A client handed no HTTP client sends through one every such client of the isolate shares, an `IOClient` over `dart:io`'s `HttpClient` (Dart's own HTTP/1.1 over BoringSSL, which reads neither the system's proxy nor a user's certificate authorities). It keeps a connection two minutes after its last request, and closes once the last client sending through it is closed.
- A mock answers the envelope the API answers: `{"data": …}` for success, `{"errors": [{"message": …, "extensions": {"code": …}}]}` with an error status for a refusal, and `content-type: application/json`. A header is read by `response.header(name)` in any letter case.
- `random:` takes a `RandomSource`, so a test pins every jitter and every drawn idempotency key.

## Control time

The client reads the time through `package:clock`, which `fake_async` overrides. A test drives retries, the session engine and a stream's silence with no time spent:

```dart
import 'dart:convert';

import 'package:fake_async/fake_async.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:mountaya_client/mountaya_client.dart';
import 'package:test/test.dart';

void main() {
  test('a 503 is asked again after its wait', () {
    fakeAsync((async) {
      var attempts = 0;
      final mountaya = Mountaya(
        credential: .publishable(key: 'pk_your_publishable_key'),
        httpClient: MockClient((request) async {
          attempts += 1;
          return attempts == 1
              ? http.Response('', 503)
              : http.Response(
                  jsonEncode({'data': <Object?>[]}),
                  200,
                  headers: {'content-type': 'application/json'},
                );
        }),
      );
      int? status;
      mountaya.studio.activities.getActivities().then(
        (response) => status = response.status,
      );
      async.elapse(const Duration(seconds: 30));
      expect(attempts, 2);
      expect(status, 200);
      mountaya.close();
    });
  });
}
```

- The client, the session engine, the event streams, `constructWebhookEvent`'s default `now`, the time slider and the search pauses read `package:clock`'s `clock`, which a zone overrides: `fakeAsync` and `withClock` both do, with no wiring.
- Flutter's `testWidgets` runs in a fake-async zone of its own: `tester.pump(duration)` moves the SDK's clock too.
- `SessionTokenEngine` mints 60 seconds before expiry; elapse past that to see the next mint. Its failed mints back off from 5 seconds, doubling, to 60.
- `ReplayLocationSource` runs on Dart's timers and the device's monotonic clock, so a replay under `fake_async` walks a route in no time.
- `withDeviceTimeZone(zone, body)` states the device's time zone for the elements' cut-offs.

## Script the map

`ScriptedMapSurface` draws a map nowhere. It answers what a renderer would, records each move and fit, and plays taps and loaded tiles:

```dart
import 'package:flutter_test/flutter_test.dart';
import 'package:mountaya_client/mountaya_client.dart';
import 'package:mountaya_elements_flutter/mountaya_elements_flutter.dart';

void main() {
  test('a tap is told as the live map tells one', () async {
    final mountaya = Mountaya(credential: .publishable(key: 'pk_your_publishable_key'));
    final map = MapEngine(mountaya);
    final surface = ScriptedMapSurface(map, canvas: const [800, 600]);

    final tapped = map.events().firstWhere((event) => event is MapEventTap);
    surface.tap([400, 300], [6.8712, 45.9231]);
    expect(await tapped, isA<MapEventTap>());

    // A fit lands where the SDK frames the box on the canvas.
    map.fitBounds([6.80, 45.85, 7.00, 46.00]);
    expect(surface.frames, hasLength(1));

    map.close();
    await mountaya.close();
  });
}
```

Under `flutter test`, `MapView` draws on a `ScriptedMapSurface` too, so a widget test of your screen needs no device.

- `ScriptedMapSurface(MapEngine engine, {List<double> canvas = const [800, 600], ZoomBounds zoomLimits})`: it plays `tap(point, position)`, `longTap`, `hover`, `leave`, `failRequest({url, status, source, cause})`, `loadTile(source)`, `loadStyle()`, `failStyle()` and `drawFrame()`, which the engine tells as the live renderer has it tell them; it records `moves` (`ScriptedMove`: `target`, `motion`), `frames` (`ScriptedFrame`: `bounds`, `fit`), `queries` and `relabelled`; `rendered` sets the features a query answers, `projection` the canvas's projection.
- Where no MapLibre platform is registered (a widget test), `MapView` draws on a scripted surface, so `testWidgets` pumps a screen holding it.
- `MapEngine` names no Flutter or MapLibre type, so its commands run on Flutter's host runner.
- Location for a map test: `Geolocation.fromFunctions(locate:, permission:)` or `InertGeolocation()` as `MapEngine(geolocation:)`.

## Script navigation

`ScriptedNavigationEngine` follows a route exactly as the device engine does, and your test answers each route request:

```dart
import 'package:mountaya_geo/mountaya_geo.dart';
import 'package:test/test.dart';

void main() {
  test('arrives at Argentière', () {
    final navigation = ScriptedNavigationEngine<String>();
    navigation.start('0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21');
    navigation.sent.single.answer(
      const NavigationRoute(
        line: [
          [6.8712, 45.9231],
          [6.9271, 45.9822],
        ],
        duration: 5400,
      ),
    );
    navigation.setPosition([6.9271, 45.9822]);
    expect(navigation.state.status, NavigationStatus.arrived);
    navigation.close();
  });
}
```

- `ScriptedNavigationEngine<Request>()` is a `NavigationEngine<Request>` on the same machine as `RouteFollowingEngine` and `DeviceNavigationEngine`: the same status, progress and arrival. It loads no native code, so it runs on the Dart VM and in a widget test alike, and each command has its effect before it returns.
- `sent` lists each `ScriptedRouteRequest` in the order it left: `request`, `answer(route)`, `fail(cause)`, `isAnswered`, `isAbandoned`. At most one is in flight; a request is answered once (`ScriptedAnswerError` otherwise), and a stop or a close abandons the request in flight.
- Hand your widgets the engine as a `NavigationEngine<Request>`, so a test swaps the scripted one in for `DeviceNavigationEngine`.

## Build errors

Every error has a public constructor, so a test builds the failure your code handles:

```dart
import 'package:mountaya_client/mountaya_client.dart';
import 'package:test/test.dart';

String advice(Object failure) => switch (failure) {
  RateLimitException(:final retryAfter?) => 'Try again in ${retryAfter.inSeconds} s.',
  NotFoundException() => 'It is gone.',
  _ => 'Something failed.',
};

void main() {
  test('a refusal reads as advice', () {
    expect(
      advice(RateLimitException(retryAfter: const Duration(seconds: 30))),
      'Try again in 30 s.',
    );
    expect(advice(NotFoundException()), 'It is gone.');
  });
}
```

- Each class of the ladder is built as `XException({errors, metadata, retryAfter, requestId, rateLimit, etag, idempotencyKey, cause, causeStackTrace})`; `ApiException.of(status, …)` answers the class a status maps to, as the client does. `ConfigurationException(message)`, `ConnectionException(cause:)` and `SelectionException(path, reason:)` too.
- A type of your own that implements `NamedException` (a failure rebuilt from another process's report) is recognised by `isMountayaException` and `isApiException` by the `name` it declares.
- The map's and navigation's exceptions build the same way: `MapException(MapExceptionKind.markerNotFound, name: 'hut')`, `LocationException(LocationExceptionKind.permissionRevoked)`, `SpeechException(SpeechExceptionKind.engineUnavailable)`, `WebhookSignatureException(WebhookSignatureReason.signature, message: …)`.

## Next steps

- [Errors and retries](https://docs.mountaya.com/en/sdks/dart/errors.md): Every error class and its status.
- [Troubleshooting](https://docs.mountaya.com/en/sdks/dart/troubleshooting.md): The errors developers hit first.
