waitFor method

Future<void> waitFor({
  1. TestStep? step,
  2. String? id,
  3. String? text,
  4. List<String> anyOf = const [],
  5. ElementTarget? target,
  6. required int timeoutMs,
  7. bool requireHitTestable = false,
  8. Future<void> onMatched(
    1. String matchedText
    )?,
})

Implementation

Future<void> waitFor({
  TestStep? step,
  String? id,
  String? text,
  List<String> anyOf = const [],
  ElementTarget? target,
  required int timeoutMs,
  bool requireHitTestable = false,
  Future<void> Function(String matchedText)? onMatched,
}) async {
  final textCandidates = <String>[
    if (text != null && text.trim().isNotEmpty) text,
    ...anyOf.where((value) => value.trim().isNotEmpty),
  ];
  if (id == null && textCandidates.isEmpty) {
    throw EnsembleTestFailure(
      'waitFor requires either "id", "text", or "anyOf"',
    );
  }

  // Inspect the current tree first. Most conditions are already available
  // after the preceding action and do not need another frame.
  if (id != null && _idMatches(id, target, requireHitTestable)) {
    return;
  }
  final initialText = firstVisibleText(textCandidates, target: target);
  if (initialText != null) {
    await _notifyTextMatched(initialText, onMatched);
    return;
  }

  final pollInterval = config.waitPollInterval <= Duration.zero
      ? const Duration(milliseconds: 1)
      : config.waitPollInterval;
  // DateTime.now() is controlled by Flutter's fake-async test clock, so it
  // advances only when pump() runs. On expensive app screens each pump may
  // take much longer than its simulated duration, making a 15s timeout take
  // minutes of wall-clock time. Stopwatch measures the actual elapsed wait.
  final stopwatch = Zone.root.run(() => Stopwatch()..start());
  while (Zone.root.run(() => stopwatch.elapsedMilliseconds) < timeoutMs) {
    await runtime.tester.pump(pollInterval);
    runtime.drainTransientFlutterDiagnostics();
    if (id != null && _idMatches(id, target, requireHitTestable)) return;
    final matchedText = firstVisibleText(textCandidates, target: target);
    if (matchedText != null) {
      await _notifyTextMatched(matchedText, onMatched);
      return;
    }
  }
  if (id != null && _idMatches(id, target, requireHitTestable)) {
    return;
  }

  final textLabel = textCandidates.isEmpty
      ? null
      : textCandidates.length == 1
          ? 'text "${textCandidates.single}"'
          : 'any text in ${textCandidates.map((t) => '"$t"').join(', ')}';
  final targetLabel = id != null && textLabel != null
      ? 'id "$id" or $textLabel'
      : id != null
          ? 'id "$id"'
          : textLabel!;
  throw EnsembleTestFailure(
    'Timed out after ${timeoutMs}ms waiting for $targetLabel. '
    '${id != null ? '${assertions.widgetIdFailureHint(id)} ${assertions.visibleTextSummary()}' : assertions.textFailureHint(textCandidates)}',
  );
}