Tutorials
Test Catalog, tabs and logout
A complete Catalog test for guest/private mounts, denied access, retained tabs, typed pop and logout cleanup.
This tutorial checks a feature journey, not whether push was called. The same Catalog module is mounted for a guest and for an account. After sign-in, Catalog and Profile keep separate stacks. Logout must clear only the private branch.
Set up and run
Use an existing Flutter project and the dependency entries from the first test. Save the complete code below as test/catalog_navigation_test.dart, then run:
flutter test test/catalog_navigation_test.dart
Expect one passing test. It exercises real navigation without rendering a window. The authentication state and resources are controlled test implementations, not a real identity provider, database or network service.
1. Keep public and private placement distinct
| Placement | Stack | Why it exists |
|---|---|---|
| Guest Catalog Mount | root | Public Home and guest Product survive account logout |
| Account Shell | account | Parent of the private branches |
| Account Catalog Mount | catalog | Its own Catalog and Product entries |
| Profile Mount | profile | A separate retained tab |
The Graph uses a parent plan to open the account shell. Mount IDs distinguish two placements of the same module; a second copy of that feature module is unnecessary.
2. Prove denial is atomic
While access.signedIn is false, the private Catalog request returns NavigationRejected. The test compares controller.value with the same saved Snapshot and checks NavigationNotCommitted on completion. It does not stop at “Guard was called.”
3. Retain the actual Product
The test enables its fake access state, opens private Catalog and Product, then switches to Profile. hasStack checks the complete Catalog stack including the committed Product Entry ID. After activateBranch, the same ID must still be on top. Matching only productRoute would miss accidental recreation.
4. Separate the result, exit and resource close
Pop from the Catalog Scope returns “chosen” through the original String ticket. The observer must record one popped exit for that exact Entry. The resource owner's separate acknowledgement is then awaited, and its close count must also be one.
The fake close is deliberately not silently idempotent: duplicate notifications should fail the test, not be concealed by the fixture.
5. Clear only the account branch
A second private Product is opened before access is disabled. resetBranch(accountScope) removes it with NavigationRemoved<String>, not NavigationPopped<String>. The account, catalog and profile stacks become empty while public Home and guest Product remain.
Finally, driver.close produces the guest Entry's sessionClosed exit. The earlier popped Product must still have only its original popped exit. Teardown separately waits for every application resource closure.
Complete file
All Destinations, Guard, Graph declarations and resource fixtures are included. Versioned source.
import 'dart:async';
import 'package:ark_navigation/ark_navigation.dart';
import 'package:ark_navigation_test/ark_navigation_test.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test(
'retains tabs, completes a product and clears only private entries',
() async {
final _AccessState access = _AccessState();
final _Resources resources = _Resources();
final NavigationTestDriver driver = NavigationTestDriver(
graph: _Scenario.graph(access),
sessionId: _Scenario.session,
lifecycleObservers: <NavigationLifecycleObserver>[resources],
);
addTearDown(() async {
driver.close();
await resources.waitForAllClosures();
});
final NavigationController controller = driver.controller;
expect(
await NavigationTestWait.committed(
const _Home().on(controller).push(),
timeout: _Scenario.deadline,
),
isA<NavigationCommitted>(),
);
final NavigationTicket<String> guest = _Product(
'guest',
).placed(mountId: _Scenario.guest).on(controller).push();
final NavigationOperationResult guestCommit =
await NavigationTestWait.committed(
guest,
timeout: _Scenario.deadline,
);
expect(guestCommit, isA<NavigationCommitted>());
final NavigationEntryId guestId =
(guestCommit as NavigationCommitted).entryId!;
// A denied request must not replace or edit any existing scope.
final NavigationSnapshot beforeDenied = controller.value;
final NavigationTicket<void> denied = const _Catalog()
.placed(mountId: _Scenario.accountCatalog)
.on(controller)
.push();
final NavigationOperationResult denial =
await NavigationTestWait.committed(
denied,
timeout: _Scenario.deadline,
);
expect(denial, isA<NavigationRejected>());
expect((denial as NavigationRejected).reason, _AccessDenial.signedOut);
expect(controller.value, same(beforeDenied));
final NavigationCompletion<void> deniedCompletion =
await NavigationTestWait.completed(
denied,
timeout: _Scenario.deadline,
);
expect(deniedCompletion, isA<NavigationNotCommitted<void>>());
expect(
(deniedCompletion as NavigationNotCommitted<void>).result,
same(denial),
);
// The test controls authentication. The helper does not log anyone in.
access.signedIn = true;
expect(
await NavigationTestWait.committed(
const _Catalog()
.placed(mountId: _Scenario.accountCatalog)
.on(controller)
.push(),
timeout: _Scenario.deadline,
),
isA<NavigationCommitted>(),
);
final NavigationTicket<String> selected = _Product(
'selected',
).placed(mountId: _Scenario.accountCatalog).on(controller).push();
final NavigationOperationResult selectedCommit =
await NavigationTestWait.committed(
selected,
timeout: _Scenario.deadline,
);
expect(selectedCommit, isA<NavigationCommitted>());
final NavigationEntryId selectedId =
(selectedCommit as NavigationCommitted).entryId!;
expect(
await NavigationTestWait.committed(
const _Profile().on(controller).push(),
timeout: _Scenario.deadline,
),
isA<NavigationCommitted>(),
);
expect(
controller.value,
NavigationTestMatchers.hasStack(_Scenario.catalogScope, <
NavigationTestEntryExpectation
>[
const NavigationTestEntryExpectation(routeId: _Scenario.catalogRoute),
NavigationTestEntryExpectation(
routeId: _Scenario.productRoute,
mountId: _Scenario.accountCatalog,
entryId: selectedId,
),
]),
);
expect(
controller.value,
NavigationTestMatchers.hasActiveChild(
_Scenario.accountScope,
_Scenario.profileScope,
),
);
expect(
await NavigationTestWait.operation(
controller.activateBranch(_Scenario.catalogScope),
timeout: _Scenario.deadline,
),
isA<NavigationCommitted>(),
);
expect(
controller.value.scope(_Scenario.catalogScope).top!.id,
selectedId,
);
expect(
controller.value,
NavigationTestMatchers.hasStack(
_Scenario.profileScope,
const <NavigationTestEntryExpectation>[
NavigationTestEntryExpectation(routeId: _Scenario.profileRoute),
],
),
);
expect(
await NavigationTestWait.operation(
controller.pop(scopeId: _Scenario.catalogScope, result: 'chosen'),
timeout: _Scenario.deadline,
),
isA<NavigationCommitted>(),
);
final NavigationCompletion<String> selectedResult =
await NavigationTestWait.completed(
selected,
timeout: _Scenario.deadline,
);
expect(selectedResult, isA<NavigationPopped<String>>());
expect((selectedResult as NavigationPopped<String>).result, 'chosen');
expect(
driver.observer,
NavigationTestMatchers.hasLifecycleExit(
sessionId: _Scenario.session,
entryId: selectedId,
reason: NavigationEntryExitReason.popped,
count: 1,
),
);
// This is the application's close acknowledgement, not didExit inference.
await resources.waitForClosure(selectedId);
expect(resources.closeCount(selectedId), 1);
final NavigationTicket<String> removed = _Product(
'removed-by-logout',
).placed(mountId: _Scenario.accountCatalog).on(controller).push();
final NavigationOperationResult removedCommit =
await NavigationTestWait.committed(
removed,
timeout: _Scenario.deadline,
);
expect(removedCommit, isA<NavigationCommitted>());
final NavigationEntryId removedId =
(removedCommit as NavigationCommitted).entryId!;
access.signedIn = false;
expect(
await NavigationTestWait.operation(
controller.resetBranch(_Scenario.accountScope),
timeout: _Scenario.deadline,
),
isA<NavigationCommitted>(),
);
expect(
await NavigationTestWait.completed(
removed,
timeout: _Scenario.deadline,
),
isA<NavigationRemoved<String>>(),
);
for (final NavigationScopeId scope in <NavigationScopeId>[
_Scenario.accountScope,
_Scenario.catalogScope,
_Scenario.profileScope,
]) {
expect(
controller.value,
NavigationTestMatchers.hasStack(
scope,
const <NavigationTestEntryExpectation>[],
),
);
}
expect(
controller.value,
NavigationTestMatchers.hasStack(
_Scenario.root,
<NavigationTestEntryExpectation>[
const NavigationTestEntryExpectation(routeId: _Scenario.homeRoute),
NavigationTestEntryExpectation(
routeId: _Scenario.productRoute,
mountId: _Scenario.guest,
entryId: guestId,
),
],
),
);
expect(
driver.observer,
NavigationTestMatchers.hasLifecycleExit(
sessionId: _Scenario.session,
entryId: removedId,
reason: NavigationEntryExitReason.removed,
count: 1,
),
);
await resources.waitForClosure(removedId);
expect(resources.closeCount(removedId), 1);
driver.close(); // Also safe when addTearDown calls it again.
await resources.waitForAllClosures();
expect(
driver.observer,
NavigationTestMatchers.hasLifecycleExit(
sessionId: _Scenario.session,
entryId: guestId,
reason: NavigationEntryExitReason.sessionClosed,
count: 1,
),
);
expect(
driver.observer,
NavigationTestMatchers.hasLifecycleExit(
sessionId: _Scenario.session,
entryId: selectedId,
reason: NavigationEntryExitReason.popped,
count: 1,
),
);
expect(resources.closeCount(guestId), 1);
expect(resources.closeCount(selectedId), 1);
expect(driver.observer, NavigationTestMatchers.hasNoObservedFailures());
},
);
}
final class _Home extends NavigationDestination<void> {
const _Home();
}
final class _Catalog extends NavigationDestination<void> {
const _Catalog();
}
final class _Profile extends NavigationDestination<void> {
const _Profile();
}
final class _Product extends NavigationDestination<String> {
_Product(this.id) {
if (id.trim().isEmpty) {
throw ArgumentError.value(id, 'id', 'Must not be blank.');
}
}
final String id;
}
final class _AccessState {
bool signedIn = false;
}
enum _AccessDenial { signedOut }
final class _AccessGuard implements NavigationGuard {
const _AccessGuard(this.access);
final _AccessState access;
@override
FutureOr<NavigationGuardDecision> evaluate(
final NavigationPolicyContext context,
) => context.phase == NavigationGuardPhase.enter && !access.signedIn
? const NavigationGuardDenied(reason: _AccessDenial.signedOut)
: const NavigationGuardAllowed();
}
// An app-owned fake resource; no disk/network/DI implementation is implied.
final class _Resource {
int closeCount = 0;
Future<void> close() async {
await Future<void>.value();
closeCount += 1;
}
}
final class _Resources implements NavigationLifecycleObserver {
final Map<NavigationEntryId, _Resource> _resources =
<NavigationEntryId, _Resource>{};
final Map<NavigationEntryId, Future<void>> _closures =
<NavigationEntryId, Future<void>>{};
@override
void didEnter(
final NavigationSessionId sessionId,
final NavigationEntrySnapshot entry,
) {
if (entry.routeId == _Scenario.productRoute) {
_resources[entry.id] = _Resource();
}
}
@override
void didExit(
final NavigationSessionId sessionId,
final NavigationEntrySnapshot entry,
final NavigationEntryExitReason reason,
) {
final _Resource? resource = _resources[entry.id];
if (resource != null) _closures[entry.id] = resource.close();
}
@override
void didReconfigure(
final NavigationSessionId sessionId,
final NavigationEntrySnapshot previous,
final NavigationEntrySnapshot next,
) {}
int closeCount(final NavigationEntryId id) => _resources[id]?.closeCount ?? 0;
Future<void> waitForClosure(final NavigationEntryId id) {
final Future<void>? closing = _closures[id];
if (closing == null) {
throw StateError('No application close acknowledgement for Entry.');
}
return closing;
}
Future<void> waitForAllClosures() async {
for (final Future<void> closing in _closures.values) {
await closing;
}
}
}
abstract final class _Scenario {
static const Duration deadline = Duration(seconds: 1);
static const NavigationSessionId session = NavigationSessionId(
'catalog-test',
);
static const NavigationScopeId root = NavigationScopeId('root');
static const NavigationScopeId accountScope = NavigationScopeId('account');
static const NavigationScopeId catalogScope = NavigationScopeId('catalog');
static const NavigationScopeId profileScope = NavigationScopeId('profile');
static const NavigationModuleId publicModule = NavigationModuleId('public');
static const NavigationModuleId catalogModule = NavigationModuleId('catalog');
static const NavigationModuleId profileModule = NavigationModuleId('profile');
static const NavigationMountId guest = NavigationMountId('guest-catalog');
static const NavigationMountId accountCatalog = NavigationMountId(
'account-catalog',
);
static const NavigationRouteId homeRoute = NavigationRouteId('home');
static const NavigationRouteId catalogRoute = NavigationRouteId('catalog');
static const NavigationRouteId productRoute = NavigationRouteId('product');
static const NavigationRouteId profileRoute = NavigationRouteId('profile');
static Widget page<D>(
final BuildContext context,
final D destination,
final NavigationEntrySnapshot entry,
) => const SizedBox();
static NavigationGraph graph(final _AccessState access) => NavigationGraph(
rootScopeId: root,
scopes: const <NavigationScopeDefinition>[
NavigationScopeDefinition(id: root),
NavigationScopeDefinition(id: accountScope, parentId: root),
NavigationScopeDefinition(id: catalogScope, parentId: accountScope),
NavigationScopeDefinition(id: profileScope, parentId: accountScope),
],
modules: <NavigationModule>[
NavigationModule(
id: publicModule,
routes: <NavigationRouteDefinitionBase>[
NavigationRouteDefinition<_Home, void>(
id: homeRoute,
pageBuilder: page<_Home>,
uriCodec: CallbackNavigationUriCodec<_Home>(
pattern: '/',
encoder: (final _Home d) => Uri(path: '/'),
decoder: (final NavigationUriMatch m) => const _Home(),
),
),
],
),
NavigationModule(
id: catalogModule,
routes: <NavigationRouteDefinitionBase>[
NavigationRouteDefinition<_Catalog, void>(
id: catalogRoute,
pageBuilder: page<_Catalog>,
uriCodec: CallbackNavigationUriCodec<_Catalog>(
pattern: '/',
encoder: (final _Catalog d) => Uri(path: '/'),
decoder: (final NavigationUriMatch m) => const _Catalog(),
),
),
NavigationRouteDefinition<_Product, String>(
id: productRoute,
pageBuilder: page<_Product>,
uriCodec: CallbackNavigationUriCodec<_Product>(
pattern: '/products/:id',
encoder: (final _Product d) =>
Uri(pathSegments: <String>['products', d.id]),
decoder: (final NavigationUriMatch m) => _Product(m.path('id')),
),
),
],
),
NavigationModule(
id: profileModule,
routes: <NavigationRouteDefinitionBase>[
NavigationRouteDefinition<_Profile, void>(
id: profileRoute,
pageBuilder: page<_Profile>,
uriCodec: CallbackNavigationUriCodec<_Profile>(
pattern: '/',
encoder: (final _Profile d) => Uri(path: '/'),
decoder: (final NavigationUriMatch m) => const _Profile(),
),
),
],
),
],
mounts: <NavigationMount>[
NavigationMount(
id: const NavigationMountId('public'),
moduleId: publicModule,
scopeId: root,
),
NavigationMount(
id: guest,
moduleId: catalogModule,
scopeId: root,
pathPrefix: '/public',
),
NavigationMount(
id: accountCatalog,
moduleId: catalogModule,
scopeId: catalogScope,
pathPrefix: '/account/catalog',
guards: <NavigationGuard>[_AccessGuard(access)],
),
NavigationMount(
id: const NavigationMountId('account-profile'),
moduleId: profileModule,
scopeId: profileScope,
pathPrefix: '/account/profile',
guards: <NavigationGuard>[_AccessGuard(access)],
),
],
);
}
When adapting it to your application
Replace _Scenario.graph with your real Graph and _AccessState with the controlled application boundary used by your tests. Keep separate assertions for policy outcome, full stack, Entry identity, typed result, lifecycle exit and resource acknowledgement.
Do not replace these assertions with sleeps or a global “idle” wait. Increase observation capacity deliberately for longer scenarios; a truncated log cannot prove an exact exit count.
For real rendered pages and fake-clock interaction, continue with Flutter host testing. The ownership guide explains pending Guards, stopped observation and failure attribution.