widget_tester.dart 1.63 KB
Newer Older
Hixie's avatar
Hixie committed
1 2 3 4 5 6
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:ui' as ui;

7 8
import 'package:quiver/testing/async.dart';
import 'package:quiver/time.dart';
9 10
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
11

12
import 'instrumentation.dart';
13

14

15 16 17 18 19 20
/// Helper class for fluter tests providing fake async.
///
/// This class extends Instrumentation to also abstract away the beginFrame
/// and async/clock access to allow writing tests which depend on the passage
/// of time without actually moving the clock forward.
class WidgetTester extends Instrumentation {
21
  WidgetTester._(FakeAsync async)
22
    : async = async,
Hixie's avatar
Hixie committed
23 24 25
      clock = async.getClock(new DateTime.utc(2015, 1, 1)) {
    timeDilation = 1.0;
    ui.window.onBeginFrame = null;
26
    runApp(new ErrorWidget()); // flush out the last build entirely
Hixie's avatar
Hixie committed
27
  }
Adam Barth's avatar
Adam Barth committed
28

29 30
  final FakeAsync async;
  final Clock clock;
Adam Barth's avatar
Adam Barth committed
31

32
  void pumpWidget(Widget widget, [ Duration duration ]) {
Adam Barth's avatar
Adam Barth committed
33
    runApp(widget);
34
    pump(duration);
35 36
  }

37 38
  void setLocale(String languageCode, String countryCode) {
    ui.Locale locale = new ui.Locale(languageCode, countryCode);
Ian Hickson's avatar
Ian Hickson committed
39
    binding.dispatchLocaleChanged(locale);
40 41 42
    async.flushMicrotasks();
  }

43 44 45
  void pump([ Duration duration ]) {
    if (duration != null)
      async.elapse(duration);
Ian Hickson's avatar
Ian Hickson committed
46 47 48
    binding.handleBeginFrame(new Duration(
      milliseconds: clock.now().millisecondsSinceEpoch)
    );
49
    async.flushMicrotasks();
Adam Barth's avatar
Adam Barth committed
50
  }
51
}
52 53 54 55 56 57

void testWidgets(callback(WidgetTester tester)) {
  new FakeAsync().run((FakeAsync async) {
    callback(new WidgetTester._(async));
  });
}