Why is Future in this test never completing?

Viewed 54

I was testing a service I wrote which returns a Future, but this weird behavior happened when I awaited the result of the future and the test never completed. Trying to reproduce the error in a minimal way, I got this:

import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('...',
      (WidgetTester tester) async {
    print('awaiting');
    await Future.delayed(Duration(seconds: 2)); // never completes
    print('done'); // not reached
  });
}

but this completes normally:

import 'package:flutter_test/flutter_test.dart';

void main() {
  test('...',
      () async {
    print('awaiting');
    await Future.delayed(Duration(seconds: 2)); // completes normally
    print('done'); // prints "done"
  });
}

why is the first one not completing, what am I missing?

1 Answers

using tester.runAsync solves the problem (I still don't know why I need to run my function within this function). It is used like this as per this github issue:

await tester.runAsync(() async {
     // run my function here
 });
Related