Flutter/Dart wait for a few seconds in unit testing

You can use awaitFuture.delayed(…)`:

test("Testing timer", () async {
    int startTime = timer.seconds;
    timer.start();

    // do something to wait for 2 seconds
    await Future.delayed(const Duration(seconds: 2), (){});

    expect(timer.seconds, startTime - 2);

});

An alternative would be fake_async with https://pub.dartlang.org/packages/clock to be able to freely manipulate the time used in the test.

Leave a Comment