Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to using FakeAsync with testWidgets?

I am trying to use FakeAsync from Dart quiver library to mock the clock of a CountDownTimer. However, when I await any async function inside the run method, it hangs.

testWidgets('Resend OTP', (WidgetTester tester) async {
  await FakeAsync().run((async) async {
    final countDownTimer = new CountdownTimer(
      new Duration(seconds: 30),
      new Duration(seconds: 1),
      stopwatch: FakeStopwatch(
          () => async.getClock(DateTime.fromMillisecondsSinceEpoch(0)).now().millisecondsSinceEpoch, 1000),
    );
    print(countDownTimer.remaining);
    print(countDownTimer.isRunning);
    await tester.pumpWidget(Container());

  });
});
like image 317
TSR Avatar asked Jun 24 '26 05:06

TSR


1 Answers

Found it, I am going to post it here anyways in case somebody needs the answer in the future:

testWidgets('Resend OTP Test concept', (WidgetTester tester) async {
    final fakeAsync = FakeAsync();
    fakeAsync.run((async) async {
      final countDownTimer = new CountdownTimer(
        new Duration(seconds: 30),
        new Duration(seconds: 1),
        stopwatch: FakeStopwatch(
            () => async.getClock(DateTime.fromMillisecondsSinceEpoch(0)).now().millisecondsSinceEpoch, 1000),
      );
      print(countDownTimer.remaining);
      print(countDownTimer.isRunning);
      await tester.pumpWidget(Container());
//      expect(true, false);

    });
    fakeAsync.flushMicrotasks();
  });

The trick is to create a variable for the FakeAsync then synchronously call fakeAsync.flushMicrotasks();

like image 71
TSR Avatar answered Jun 26 '26 19:06

TSR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!