widget_tester_test.dart 21.2 KB
Newer Older
1 2 3 4
// Copyright 2016 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.

5
import 'dart:async';
6
import 'dart:io';
7
import 'dart:ui';
8

9 10
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
11
import 'package:flutter/rendering.dart';
12
import 'package:flutter_test/flutter_test.dart';
13 14
import 'package:test_api/test_api.dart' as test_package;
import 'package:test_api/src/frontend/async_matcher.dart' show AsyncMatcher;
15

16 17 18
const List<Widget> fooBarTexts = <Text>[
  Text('foo', textDirection: TextDirection.ltr),
  Text('bar', textDirection: TextDirection.ltr),
Ian Hickson's avatar
Ian Hickson committed
19 20
];

21
void main() {
22 23
  group('expectLater', () {
    testWidgets('completes when matcher completes', (WidgetTester tester) async {
24 25
      final Completer<void> completer = Completer<void>();
      final Future<void> future = expectLater(null, FakeMatcher(completer));
26 27 28
      String result;
      future.then<void>((void value) {
        result = '123';
29
      });
30
      test_package.expect(result, isNull);
31
      completer.complete();
32
      test_package.expect(result, isNull);
33 34
      await future;
      await tester.pump();
35
      test_package.expect(result, '123');
36
    });
37 38

    testWidgets('respects the skip flag', (WidgetTester tester) async {
39 40
      final Completer<void> completer = Completer<void>();
      final Future<void> future = expectLater(null, FakeMatcher(completer), skip: 'testing skip');
41
      bool completed = false;
42
      future.then<void>((_) {
43 44 45 46 47
        completed = true;
      });
      test_package.expect(completed, isFalse);
      await future;
      test_package.expect(completed, isTrue);
48
    });
49 50
  });

51
  group('findsOneWidget', () {
52
    testWidgets('finds exactly one widget', (WidgetTester tester) async {
Ian Hickson's avatar
Ian Hickson committed
53
      await tester.pumpWidget(const Text('foo', textDirection: TextDirection.ltr));
54
      expect(find.text('foo'), findsOneWidget);
55 56
    });

57
    testWidgets('fails with a descriptive message', (WidgetTester tester) async {
58 59
      TestFailure failure;
      try {
60
        expect(find.text('foo', skipOffstage: false), findsOneWidget);
61
      } catch (e) {
62 63 64 65
        failure = e;
      }

      expect(failure, isNotNull);
66
      final String message = failure.message;
67 68 69
      expect(message, contains('Expected: exactly one matching node in the widget tree\n'));
      expect(message, contains('Actual: ?:<zero widgets with text "foo">\n'));
      expect(message, contains('Which: means none were found but one was expected\n'));
70 71 72
    });
  });

73
  group('findsNothing', () {
74
    testWidgets('finds no widgets', (WidgetTester tester) async {
75
      expect(find.text('foo'), findsNothing);
76 77
    });

78
    testWidgets('fails with a descriptive message', (WidgetTester tester) async {
Ian Hickson's avatar
Ian Hickson committed
79
      await tester.pumpWidget(const Text('foo', textDirection: TextDirection.ltr));
80 81 82

      TestFailure failure;
      try {
83
        expect(find.text('foo', skipOffstage: false), findsNothing);
84
      } catch (e) {
85 86 87 88
        failure = e;
      }

      expect(failure, isNotNull);
89
      final String message = failure.message;
90 91

      expect(message, contains('Expected: no matching nodes in the widget tree\n'));
92
      expect(message, contains('Actual: ?:<exactly one widget with text "foo": Text("foo", textDirection: ltr)>\n'));
93
      expect(message, contains('Which: means one was found but none were expected\n'));
94
    });
95 96

    testWidgets('fails with a descriptive message when skipping', (WidgetTester tester) async {
Ian Hickson's avatar
Ian Hickson committed
97
      await tester.pumpWidget(const Text('foo', textDirection: TextDirection.ltr));
98 99 100 101

      TestFailure failure;
      try {
        expect(find.text('foo'), findsNothing);
102
      } catch (e) {
103 104 105 106
        failure = e;
      }

      expect(failure, isNotNull);
107
      final String message = failure.message;
108 109

      expect(message, contains('Expected: no matching nodes in the widget tree\n'));
110
      expect(message, contains('Actual: ?:<exactly one widget with text "foo" (ignoring offstage widgets): Text("foo", textDirection: ltr)>\n'));
111 112
      expect(message, contains('Which: means one was found but none were expected\n'));
    });
113 114

    testWidgets('pumping', (WidgetTester tester) async {
Ian Hickson's avatar
Ian Hickson committed
115
      await tester.pumpWidget(const Text('foo', textDirection: TextDirection.ltr));
116 117
      int count;

118
      final AnimationController test = AnimationController(
119 120 121
        duration: const Duration(milliseconds: 5100),
        vsync: tester,
      );
122 123
      count = await tester.pumpAndSettle(const Duration(seconds: 1));
      expect(count, 1); // it always pumps at least one frame
124 125

      test.forward(from: 0.0);
126
      count = await tester.pumpAndSettle(const Duration(seconds: 1));
127 128 129 130 131 132 133 134 135 136 137
      // 1 frame at t=0, starting the animation
      // 1 frame at t=1
      // 1 frame at t=2
      // 1 frame at t=3
      // 1 frame at t=4
      // 1 frame at t=5
      // 1 frame at t=6, ending the animation
      expect(count, 7);

      test.forward(from: 0.0);
      await tester.pump(); // starts the animation
138
      count = await tester.pumpAndSettle(const Duration(seconds: 1));
139 140 141 142 143
      expect(count, 6);

      test.forward(from: 0.0);
      await tester.pump(); // starts the animation
      await tester.pump(); // has no effect
144
      count = await tester.pumpAndSettle(const Duration(seconds: 1));
145 146
      expect(count, 6);
    });
147
  });
148

149 150
  group('find.byElementPredicate', () {
    testWidgets('fails with a custom description in the message', (WidgetTester tester) async {
Ian Hickson's avatar
Ian Hickson committed
151
      await tester.pumpWidget(const Text('foo', textDirection: TextDirection.ltr));
152

153
      const String customDescription = 'custom description';
154 155 156
      TestFailure failure;
      try {
        expect(find.byElementPredicate((_) => false, description: customDescription), findsOneWidget);
157
      } catch (e) {
158 159 160 161 162 163 164 165 166 167
        failure = e;
      }

      expect(failure, isNotNull);
      expect(failure.message, contains('Actual: ?:<zero widgets with $customDescription'));
    });
  });

  group('find.byWidgetPredicate', () {
    testWidgets('fails with a custom description in the message', (WidgetTester tester) async {
Ian Hickson's avatar
Ian Hickson committed
168
      await tester.pumpWidget(const Text('foo', textDirection: TextDirection.ltr));
169

170
      const String customDescription = 'custom description';
171 172 173
      TestFailure failure;
      try {
        expect(find.byWidgetPredicate((_) => false, description: customDescription), findsOneWidget);
174
      } catch (e) {
175 176 177 178 179 180 181
        failure = e;
      }

      expect(failure, isNotNull);
      expect(failure.message, contains('Actual: ?:<zero widgets with $customDescription'));
    });
  });
182 183 184

  group('find.descendant', () {
    testWidgets('finds one descendant', (WidgetTester tester) async {
185
      await tester.pumpWidget(Row(
186 187
        textDirection: TextDirection.ltr,
        children: <Widget>[
188
          Column(children: fooBarTexts),
189 190
        ],
      ));
191 192 193

      expect(find.descendant(
        of: find.widgetWithText(Row, 'foo'),
194
        matching: find.text('bar'),
195 196 197 198
      ), findsOneWidget);
    });

    testWidgets('finds two descendants with different ancestors', (WidgetTester tester) async {
199
      await tester.pumpWidget(Row(
200 201
        textDirection: TextDirection.ltr,
        children: <Widget>[
202 203
          Column(children: fooBarTexts),
          Column(children: fooBarTexts),
204 205
        ],
      ));
206 207 208

      expect(find.descendant(
        of: find.widgetWithText(Column, 'foo'),
209
        matching: find.text('bar'),
210 211 212 213
      ), findsNWidgets(2));
    });

    testWidgets('fails with a descriptive message', (WidgetTester tester) async {
214
      await tester.pumpWidget(Row(
215 216
        textDirection: TextDirection.ltr,
        children: <Widget>[
217
          Column(children: const <Text>[Text('foo', textDirection: TextDirection.ltr)]),
Ian Hickson's avatar
Ian Hickson committed
218
          const Text('bar', textDirection: TextDirection.ltr),
219 220
        ],
      ));
221 222 223 224 225

      TestFailure failure;
      try {
        expect(find.descendant(
          of: find.widgetWithText(Column, 'foo'),
226
          matching: find.text('bar'),
227 228 229 230 231 232 233
        ), findsOneWidget);
      } catch (e) {
        failure = e;
      }

      expect(failure, isNotNull);
      expect(
234
        failure.message,
235 236 237
        contains(
          'Actual: ?:<zero widgets with text "bar" that has ancestor(s) with type "Column" which is an ancestor of text "foo"',
        ),
238
      );
239
    });
240
  });
241

242 243
  group('find.ancestor', () {
    testWidgets('finds one ancestor', (WidgetTester tester) async {
244
      await tester.pumpWidget(Row(
245 246
        textDirection: TextDirection.ltr,
        children: <Widget>[
247
          Column(children: fooBarTexts),
248 249
        ],
      ));
250

251 252 253 254 255 256 257 258
      expect(find.ancestor(
        of: find.text('bar'),
        matching: find.widgetWithText(Row, 'foo'),
      ), findsOneWidget);
    });

    testWidgets('finds two matching ancestors, one descendant', (WidgetTester tester) async {
      await tester.pumpWidget(
259
        Directionality(
260
          textDirection: TextDirection.ltr,
261
          child: Row(
262
            children: <Widget>[
263
              Row(children: fooBarTexts),
264 265 266 267 268 269 270
            ],
          ),
        ),
      );

      expect(find.ancestor(
        of: find.text('bar'),
271
        matching: find.byType(Row),
272 273 274 275
      ), findsNWidgets(2));
    });

    testWidgets('fails with a descriptive message', (WidgetTester tester) async {
276
      await tester.pumpWidget(Row(
277 278
        textDirection: TextDirection.ltr,
        children: <Widget>[
279
          Column(children: const <Text>[Text('foo', textDirection: TextDirection.ltr)]),
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
          const Text('bar', textDirection: TextDirection.ltr),
        ],
      ));

      TestFailure failure;
      try {
        expect(find.ancestor(
          of: find.text('bar'),
          matching: find.widgetWithText(Column, 'foo'),
        ), findsOneWidget);
      } catch (e) {
        failure = e;
      }

      expect(failure, isNotNull);
      expect(
        failure.message,
297 298 299
        contains(
          'Actual: ?:<zero widgets with type "Column" which is an ancestor of text "foo" which is an ancestor of text "bar"',
        ),
300 301 302 303
      );
    });

    testWidgets('Root not matched by default', (WidgetTester tester) async {
304
      await tester.pumpWidget(Row(
305 306
        textDirection: TextDirection.ltr,
        children: <Widget>[
307
          Column(children: fooBarTexts),
308 309 310 311 312 313
        ],
      ));

      expect(find.ancestor(
        of: find.byType(Column),
        matching: find.widgetWithText(Column, 'foo'),
314 315 316 317
      ), findsNothing);
    });

    testWidgets('Match the root', (WidgetTester tester) async {
318
      await tester.pumpWidget(Row(
319 320
        textDirection: TextDirection.ltr,
        children: <Widget>[
321
          Column(children: fooBarTexts),
322 323
        ],
      ));
324 325

      expect(find.descendant(
326 327
        of: find.byType(Column),
        matching: find.widgetWithText(Column, 'foo'),
328 329 330
        matchRoot: true,
      ), findsOneWidget);
    });
331
  });
332

333
  group('pageBack', () {
334
    testWidgets('fails when there are no back buttons', (WidgetTester tester) async {
335
      await tester.pumpWidget(Container());
336 337 338

      expect(
        expectAsync0(tester.pageBack),
339
        throwsA(isInstanceOf<TestFailure>()),
340 341 342 343 344
      );
    });

    testWidgets('successfully taps material back buttons', (WidgetTester tester) async {
      await tester.pumpWidget(
345 346 347
        MaterialApp(
          home: Center(
            child: Builder(
348
              builder: (BuildContext context) {
349
                return RaisedButton(
350 351
                  child: const Text('Next'),
                  onPressed: () {
352
                    Navigator.push<void>(context, MaterialPageRoute<void>(
353
                      builder: (BuildContext context) {
354 355
                        return Scaffold(
                          appBar: AppBar(
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
                            title: const Text('Page 2'),
                          ),
                        );
                      },
                    ));
                  },
                );
              } ,
            ),
          ),
        ),
      );

      await tester.tap(find.text('Next'));
      await tester.pump();
      await tester.pump(const Duration(milliseconds: 400));

      await tester.pageBack();
      await tester.pump();
      await tester.pump(const Duration(milliseconds: 400));

      expect(find.text('Next'), findsOneWidget);
      expect(find.text('Page 2'), findsNothing);
    });

    testWidgets('successfully taps cupertino back buttons', (WidgetTester tester) async {
      await tester.pumpWidget(
383 384 385
        MaterialApp(
          home: Center(
            child: Builder(
386
              builder: (BuildContext context) {
387
                return CupertinoButton(
388 389
                  child: const Text('Next'),
                  onPressed: () {
390
                    Navigator.push<void>(context, CupertinoPageRoute<void>(
391
                      builder: (BuildContext context) {
392
                        return CupertinoPageScaffold(
393
                          navigationBar: const CupertinoNavigationBar(
394
                            middle: Text('Page 2'),
395
                          ),
396
                          child: Container(),
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
                        );
                      },
                    ));
                  },
                );
              } ,
            ),
          ),
        ),
      );

      await tester.tap(find.text('Next'));
      await tester.pump();
      await tester.pump(const Duration(milliseconds: 400));

      await tester.pageBack();
      await tester.pump();
414
      await tester.pumpAndSettle();
415 416 417 418 419 420

      expect(find.text('Next'), findsOneWidget);
      expect(find.text('Page 2'), findsNothing);
    });
  });

421
  testWidgets('hasRunningAnimations control test', (WidgetTester tester) async {
422
    final AnimationController controller = AnimationController(
423
      duration: const Duration(seconds: 1),
424
      vsync: const TestVSync(),
425 426 427 428 429 430 431 432 433 434 435
    );
    expect(tester.hasRunningAnimations, isFalse);
    controller.forward();
    expect(tester.hasRunningAnimations, isTrue);
    controller.stop();
    expect(tester.hasRunningAnimations, isFalse);
    controller.forward();
    expect(tester.hasRunningAnimations, isTrue);
    await tester.pumpAndSettle();
    expect(tester.hasRunningAnimations, isFalse);
  });
436 437

  testWidgets('pumpAndSettle control test', (WidgetTester tester) async {
438
    final AnimationController controller = AnimationController(
439
      duration: const Duration(minutes: 525600),
440
      vsync: const TestVSync(),
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
    );
    expect(await tester.pumpAndSettle(), 1);
    controller.forward();
    try {
      await tester.pumpAndSettle();
      expect(true, isFalse);
    } catch (e) {
      expect(e, isFlutterError);
    }
    controller.stop();
    expect(await tester.pumpAndSettle(), 1);
    controller.duration = const Duration(seconds: 1);
    controller.forward();
    expect(await tester.pumpAndSettle(const Duration(milliseconds: 300)), 5); // 0, 300, 600, 900, 1200ms
  });
456 457 458 459 460 461 462 463 464 465 466

  group('runAsync', () {
    testWidgets('works with no async calls', (WidgetTester tester) async {
      String value;
      await tester.runAsync(() async {
        value = '123';
      });
      expect(value, '123');
    });

    testWidgets('works with real async calls', (WidgetTester tester) async {
467
      final StringBuffer buf = StringBuffer('1');
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
      await tester.runAsync(() async {
        buf.write('2');
        await Directory.current.stat();
        buf.write('3');
      });
      buf.write('4');
      expect(buf.toString(), '1234');
    });

    testWidgets('propagates return values', (WidgetTester tester) async {
      final String value = await tester.runAsync<String>(() async {
        return '123';
      });
      expect(value, '123');
    });

    testWidgets('reports errors via framework', (WidgetTester tester) async {
      final String value = await tester.runAsync<String>(() async {
486
        throw ArgumentError();
487 488 489 490 491 492
      });
      expect(value, isNull);
      expect(tester.takeException(), isArgumentError);
    });

    testWidgets('disallows re-entry', (WidgetTester tester) async {
493
      final Completer<void> completer = Completer<void>();
494
      tester.runAsync<void>(() => completer.future);
495
      expect(() => tester.runAsync(() async { }), throwsA(isInstanceOf<TestFailure>()));
496 497
      completer.complete();
    });
498 499

    testWidgets('maintains existing zone values', (WidgetTester tester) async {
500
      final Object key = Object();
501
      await runZoned<Future<void>>(() {
502
        expect(Zone.current[key], 'abczed');
503
        return tester.runAsync<void>(() async {
504 505 506 507 508 509
          expect(Zone.current[key], 'abczed');
        });
      }, zoneValues: <dynamic, dynamic>{
        key: 'abczed',
      });
    });
510
  });
511 512 513

  testWidgets('showKeyboard can be called twice', (WidgetTester tester) async {
    await tester.pumpWidget(
514 515 516 517
      MaterialApp(
        home: Material(
          child: Center(
            child: TextFormField(),
518 519 520 521 522
          ),
        ),
      ),
    );
    await tester.showKeyboard(find.byType(TextField));
523
    await tester.testTextInput.receiveAction(TextInputAction.done);
524 525
    await tester.pump();
    await tester.showKeyboard(find.byType(TextField));
526
    await tester.testTextInput.receiveAction(TextInputAction.done);
527 528 529 530 531
    await tester.pump();
    await tester.showKeyboard(find.byType(TextField));
    await tester.showKeyboard(find.byType(TextField));
    await tester.pump();
  });
532 533 534 535

  group('getSemanticsData', () {
    testWidgets('throws when there are no semantics', (WidgetTester tester) async {
      await tester.pumpWidget(
536 537
        const MaterialApp(
          home: Scaffold(
538
            body: Text('hello'),
539 540 541 542
          ),
        ),
      );

543
      expect(() => tester.getSemantics(find.text('hello')),
544 545 546 547 548 549 550
        throwsA(isInstanceOf<StateError>()));
    });

    testWidgets('throws when there are multiple results from the finder', (WidgetTester tester) async {
      final SemanticsHandle semanticsHandle = tester.ensureSemantics();

      await tester.pumpWidget(
551 552 553
        MaterialApp(
          home: Scaffold(
            body: Row(
554
              children: const <Widget>[
555 556
                Text('hello'),
                Text('hello'),
557 558 559 560 561 562
              ],
            ),
          ),
        ),
      );

563
      expect(() => tester.getSemantics(find.text('hello')),
564 565 566
          throwsA(isInstanceOf<StateError>()));
      semanticsHandle.dispose();
    });
567

568 569 570 571
    testWidgets('Returns the correct SemanticsData', (WidgetTester tester) async {
      final SemanticsHandle semanticsHandle = tester.ensureSemantics();

      await tester.pumpWidget(
572 573 574 575
        MaterialApp(
          home: Scaffold(
            body: Container(
              child: OutlineButton(
576
                  onPressed: () { },
577
                  child: const Text('hello'),
578 579 580 581 582 583
              ),
            ),
          ),
        ),
      );

584 585
      final SemanticsNode node = tester.getSemantics(find.text('hello'));
      final SemanticsData semantics = node.getSemanticsData();
586 587 588 589 590 591
      expect(semantics.label, 'hello');
      expect(semantics.hasAction(SemanticsAction.tap), true);
      expect(semantics.hasFlag(SemanticsFlag.isButton), true);
      semanticsHandle.dispose();
    });

592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
    testWidgets('Can enable semantics for tests via semanticsEnabled', (WidgetTester tester) async {
      await tester.pumpWidget(
        MaterialApp(
          home: Scaffold(
            body: Container(
              child: OutlineButton(
                  onPressed: () { },
                  child: const Text('hello'),
              ),
            ),
          ),
        ),
      );

      final SemanticsNode node = tester.getSemantics(find.text('hello'));
      final SemanticsData semantics = node.getSemanticsData();
      expect(semantics.label, 'hello');
      expect(semantics.hasAction(SemanticsAction.tap), true);
      expect(semantics.hasFlag(SemanticsFlag.isButton), true);
    }, semanticsEnabled: true);

613 614
    testWidgets('Returns merged SemanticsData', (WidgetTester tester) async {
      final SemanticsHandle semanticsHandle = tester.ensureSemantics();
615
      const Key key = Key('test');
616
      await tester.pumpWidget(
617 618 619
        MaterialApp(
          home: Scaffold(
            body: Semantics(
620
              label: 'A',
621
              child: Semantics(
622
                label: 'B',
623
                child: Semantics(
624 625
                  key: key,
                  label: 'C',
626
                  child: Container(),
627 628
                ),
              ),
629
            ),
630 631 632 633
          ),
        ),
      );

634 635
      final SemanticsNode node = tester.getSemantics(find.byKey(key));
      final SemanticsData semantics = node.getSemanticsData();
636 637 638 639
      expect(semantics.label, 'A\nB\nC');
      semanticsHandle.dispose();
    });
  });
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663

  group('ensureVisible', () {
    testWidgets('scrolls to make widget visible', (WidgetTester tester) async {
      await tester.pumpWidget(
        MaterialApp(
          home: Scaffold(
            body: ListView.builder(
              itemCount: 20,
              shrinkWrap: true,
              itemBuilder: (BuildContext context, int i) => ListTile(title: Text('Item $i')),
           ),
         ),
        ),
      );

      // Make sure widget isn't on screen
      expect(find.text('Item 15', skipOffstage: true), findsNothing);

      await tester.ensureVisible(find.text('Item 15', skipOffstage: false));
      await tester.pumpAndSettle();

      expect(find.text('Item 15', skipOffstage: true), findsOneWidget);
    });
  });
664
}
665 666 667 668 669 670 671 672

class FakeMatcher extends AsyncMatcher {
  FakeMatcher(this.completer);

  final Completer<void> completer;

  @override
  Future<String> matchAsync(dynamic object) {
673
    return completer.future.then<String>((void value) {
674 675 676 677 678 679 680
      return object?.toString();
    });
  }

  @override
  Description describe(Description description) => description.add('--fake--');
}