本文へ移動
cccskills
無料GitHub で公開

flutter-async-test-unhandled-future-rejection

Fix flaky Flutter/Dart tests that fail in CI but pass locally due to unhandled Future rejections. Use when: (1) Test passes locally but fails in CI with cryptic errors, (2) Test creates Futures that will throw errors (e.g., network calls to fake URLs), (3) Even with .catchError() at the end, test still fails, (4) Error message shows test name but truncated error like "ROR]" or "[ERROR]". Solution: Avoid creating Futures that will reject; test state machine behavior with synchronous operations instead.

インストール方法を見る

含まれるファイル(1)

  • SKILL.md6.2 KB

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

Flutter Async Test Unhandled Future Rejection

Problem

Tests that create Futures which will reject (throw errors) can fail in CI even when:

  • You catch the error with .catchError() at the end
  • You use try/catch around the await
  • The test passes locally

The Flutter/Dart test framework detects "unhandled" Future rejections during test execution, even if you plan to handle them later. This causes flaky tests that pass locally but fail in CI due to timing differences.

Context / Trigger Conditions

Symptoms:

  • Test passes locally with flutter test but fails in CI
  • Error message is truncated or cryptic (e.g., "ROR]" instead of "[ERROR]")
  • Test name appears in error output but no clear assertion failure
  • Test involves creating Futures to URLs/resources that don't exist
  • Using patterns like:
    final future = someAsyncOperation(); // This will throw
    // ... do assertions ...
    await future.catchError((_) {}); // Too late - already flagged as unhandled
    

Common scenarios:

  • Testing that a method can only be called once (state guards)
  • Testing timeout/cancellation behavior
  • Testing error handling paths
  • Any test that intentionally triggers errors in async code

Solution

Don't create Futures that will reject - test the state machine directly

Instead of:

test('start throws if already started', () async {
  final session = SomeSession(url: 'wss://fake.url');

  // BAD: This Future will reject when connection fails
  final startFuture = session.start();

  // Even this won't help - rejection already detected
  await Future.delayed(Duration.zero);

  expect(() => session.start(), throwsA(isA<StateError>()));

  // Too late to catch - test already failed
  await startFuture.catchError((_) {});
});

Do this:

test('start throws if already started', () {
  // GOOD: Completely synchronous, no network calls
  final session = SomeSession(url: 'wss://example.com');

  // Use a synchronous state transition to exit the "startable" state
  session.cancel(); // Transitions state without network call

  // Now test that start() throws when not in initial state
  expect(
    () => session.start(),
    throwsA(isA<StateError>()),
  );

  session.dispose();
});

Alternative approaches if you must use async

Option 1: Wrap the Future creation in a zone that ignores errors

test('handles async error', () async {
  late Future<void> errorFuture;

  await runZonedGuarded(() async {
    errorFuture = operationThatWillFail();
    // Do synchronous assertions here
  }, (error, stack) {
    // Ignore expected errors
  });
});

Option 2: Use expectLater for Futures that should fail

test('operation fails with specific error', () async {
  // Let the test framework know this Future SHOULD fail
  await expectLater(
    operationThatWillFail(),
    throwsA(isA<SomeError>()),
  );
});

Option 3: Mock the async dependency

test('start throws if already started', () async {
  final mockRelay = MockRelay();
  when(mockRelay.connect()).thenAnswer((_) async => {}); // Never fails

  final session = SomeSession(relay: mockRelay);
  await session.start();

  expect(() => session.start(), throwsA(isA<StateError>()));
});

Verification

  1. Test passes locally: flutter test path/to/test.dart
  2. Test passes in CI (check GitHub Actions / other CI)
  3. Test is deterministic - run 10x with --repeat=10 flag

Example

Before (flaky):

test('NostrConnectSession start throws if already started', () async {
  final session = NostrConnectSession(relays: ['wss://relay.example.com']);

  // This creates a Future that will reject when relay connection fails
  final startFuture = session.start();

  // State changed synchronously, but Future rejection is pending
  expect(session.state, isNot(equals(NostrConnectState.idle)));
  expect(() => session.start(), throwsA(isA<StateError>()));

  session.cancel();
  session.dispose();

  // This doesn't help - rejection already flagged by test framework
  await startFuture.catchError((_) {});
});

After (reliable):

test('NostrConnectSession start throws if already started', () {
  // Completely synchronous - no Futures that can reject
  final session = NostrConnectSession(relays: ['wss://relay.example.com']);

  expect(session.state, equals(NostrConnectState.idle));

  // Use cancel() to transition out of idle state synchronously
  session.cancel();
  expect(session.state, equals(NostrConnectState.cancelled));

  // Now start() throws because we're not in idle state
  expect(
    () => session.start(),
    throwsA(
      isA<StateError>().having(
        (e) => e.message,
        'message',
        contains('already started'),
      ),
    ),
  );

  session.dispose();
});

Notes

  • This issue is more common in CI because of different timing characteristics
  • The truncated error messages (like "ROR]") happen because CI output gets cut off
  • Local tests may pass because the garbage collector hasn't run yet
  • This is different from the "A Timer is still pending" error (see flutter-dispose-timer-test-failure skill)
  • When testing state machines, prefer testing state transitions over testing async behavior
  • If you need to test actual async/network behavior, use proper mocking

Related Skills

  • flutter-dispose-timer-test-failure: For timer-related test failures
  • riverpod-ref-in-provider-lifecycle: For async callback issues in Riverpod providers

References

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

Fix ArgoCD ExternalSecret deployment failing with "namespace X is not permitted in project Y". Use when: (1) ExternalSecret shows OutOfSync in ArgoCD but won't sync, (2) ArgoCD application status shows "namespace X is not permitted in project 'infrastructure'", (3) ExternalSecret targets a namespace managed by a different ArgoCD project, (4) Using apps-of-apps pattern with separate infrastructure and application projects.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月13日 更新

Art direction for any content — reads text, PDF, Word, HTML, PPT, then proposes 2-3 creative directions with photography style, mood, and visual language. After selection, generates AI image prompts and visual briefs section-by-section. Use when the user shares content and needs visual direction, image sourcing, or creative direction for any material.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月13日 更新

Fix "Null check operator used on a null value" errors when an object is set to null during an async await. Use when: (1) Object reference is nullified while awaiting, (2) Code accesses object with ! after await returns, (3) Cancel/dispose operations run concurrently with async operations on same object. Solution: capture local reference before await.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月13日 更新

Add custom metadata headers (x-amz-meta-*) to AWS v4 signed requests for GCS S3-compatible API. Use when: (1) Adding custom metadata to GCS uploads via S3 API, (2) Getting signature mismatch errors after adding new headers, (3) x-amz-meta-* headers being ignored or causing 403 errors. Custom headers MUST be included in canonical headers and signed headers list.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月13日 更新

Fix password/secret authentication failures caused by trailing newlines when creating Google Cloud secrets (or similar) with bash here-strings. Use when: (1) Password authentication fails with correct password, (2) Secret created with `<<< "value"` syntax, (3) Error like "password authentication failed" or "invalid token" despite correct value. Bash here-strings (`<<<`) add a trailing newline that corrupts secrets.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月13日 更新

Fix silent video/media processing failures caused by URL extraction code that filters on file extensions (.mp4, .webm, .webp). Use when: (1) Media moderation, transcoding, or analysis silently skips files from Blossom or content-addressed storage servers, (2) URL extraction from Nostr event tags (imeta, r tags) drops URLs without recognized extensions, (3) CDN fallback URLs append .mp4 but the actual server uses extensionless content-addressed paths like /{sha256}. Common in Nostr video events (kind 34236) where different clients use different URL formats.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月13日 更新

divinevideo のスキルをすべて見る

このスキルの問題を報告する