|
| 1 | +import 'package:checks/checks.dart'; |
| 2 | +import 'package:flutter/material.dart'; |
| 3 | +import 'package:flutter_test/flutter_test.dart'; |
| 4 | + |
| 5 | +/// In a widget test, check that showErrorDialog was called with the right text. |
| 6 | +/// |
| 7 | +/// Checks for an error dialog matching an expected title |
| 8 | +/// and, optionally, matching an expected message. Fails if none is found. |
| 9 | +/// |
| 10 | +/// On success, returns the widget's "OK" button. |
| 11 | +/// Dismiss the dialog by calling `tester.tap(find.byWidget(okButton))`. |
| 12 | +Widget checkErrorDialog(WidgetTester tester, { |
| 13 | + required String expectedTitle, |
| 14 | + String? expectedMessage, |
| 15 | +}) { |
| 16 | + final alertDialogList = tester.widgetList<AlertDialog>(find.byWidgetPredicate((widget) { |
| 17 | + if (widget is! AlertDialog) { |
| 18 | + return false; |
| 19 | + } |
| 20 | + if (widget.title is! Text || (widget.title as Text).data != expectedTitle) { |
| 21 | + return false; |
| 22 | + } |
| 23 | + if ( |
| 24 | + expectedMessage != null |
| 25 | + && ( |
| 26 | + widget.content == null |
| 27 | + || tester.widgetList( |
| 28 | + find.descendant(of: find.byWidget(widget.content!), |
| 29 | + matching: find.text(expectedMessage)) |
| 30 | + ).isEmpty |
| 31 | + ) |
| 32 | + ) { |
| 33 | + return false; |
| 34 | + } |
| 35 | + return true; |
| 36 | + })); |
| 37 | + // TODO: Can we give a more helpful, to-the-point error message than this: |
| 38 | + // |
| 39 | + // The following TestFailure was thrown running a test: |
| 40 | + // Expected: a Iterable<AlertDialog> that: |
| 41 | + // has length that: |
| 42 | + // equals <1> |
| 43 | + // Actual: a Iterable<AlertDialog> that: |
| 44 | + // has length that: |
| 45 | + // Actual: <0> |
| 46 | + // Which: are not equal |
| 47 | + check(alertDialogList).length.equals(1); |
| 48 | + |
| 49 | + return tester.widget( |
| 50 | + find.descendant(of: find.byWidget(alertDialogList.single), |
| 51 | + matching: find.byWidgetPredicate((widget) { |
| 52 | + return widget is TextButton && widget.child is Text && (widget.child as Text).data == 'OK'; |
| 53 | + }))); |
| 54 | +} |
0 commit comments