Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter/Dart wait for a few seconds in unit testing

I am writing a timer app. In unit testing how do I wait for few seconds to test if my timer is working properly?

// I want something like this.
test("Testing timer", () {
    int startTime = timer.seconds;
    timer.start();

    // do something to wait for 2 seconds

    expect(timer.seconds, startTime - 2);

});
like image 651
Ragas Avatar asked Jan 08 '19 09:01

Ragas


Video Answer


2 Answers

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.

like image 124
Günter Zöchbauer Avatar answered Oct 21 '22 00:10

Günter Zöchbauer


To do that you can use a fake_async package. that allow in a flutter to Fake asynchronous events such as timers and microtasks for deterministic testing

This package provides a FakeAsync class, which makes it easy to deterministically test code that uses asynchronous features like Futures, Streams, Timers, and microtasks. It creates an environment in which the user can explicitly control Dart's notion of the "current time". When the time is advanced, FakeAsync fires all asynchronous events that are scheduled for that time period without actually needing the test to wait for real-time to elapse.

For example:

import 'dart:async';  import 'package:fake_async/fake_async.dart'; import 'package:test/test.dart';  void main() {   test("Future.timeout() throws an error once the timeout is up", () {     // Any code run within [fakeAsync] is run within the context of the     // [FakeAsync] object passed to the callback.     fakeAsync((async) {       // All asynchronous features that rely on timing are automatically       // controlled by [fakeAsync].       expect(new Completer().future.timeout(new Duration(seconds: 5)),           throwsA(new isInstanceOf<TimeoutException>()));        // This will cause the timeout above to fire immediately, without waiting       // 5 seconds of real time.       async.elapse(new Duration(seconds: 5));     });   }); } 
like image 30
Paresh Mangukiya Avatar answered Oct 05 '22 03:10

Paresh Mangukiya