Skip to content

Instantly share code, notes, and snippets.

@ben-xD
Last active November 20, 2022 16:07
Show Gist options
  • Save ben-xD/a7e19a0233f716dd3b849d5d1f71bde9 to your computer and use it in GitHub Desktop.
Save ben-xD/a7e19a0233f716dd3b849d5d1f71bde9 to your computer and use it in GitHub Desktop.
Widget-testing `showDialog`/`AlertDialog` in Flutter
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter/material.dart';
const buttonKey = Key("button");
const alertDialogKey = Key("alertDialog");
class MyApp extends StatelessWidget {
showAppDialog(BuildContext context) async {
print("Showing app dialog");
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
key: alertDialogKey,
title: const Text(
"A alert dialog.",
),
icon: const Icon(Icons.catching_pokemon),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text("Oops"),
),
],
);
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Dialog',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(body: SafeArea(child: Builder(builder: (context) {
return TextButton(
key: buttonKey,
child: const Text("Show dialog"),
onPressed: () async => await showAppDialog(context),
);
}))),
);
}
}
void mainTest() {
testWidgets(
"When button is pressed, dialog is shown.",
(tester) async {
final widget = MyApp();
await tester.pumpWidget(widget);
final button = find.byKey(buttonKey);
expect(button, findsOneWidget);
await tester.runAsync(() async {
await tester.tap(button);
// Or alternatively press then "up":
// final response = await tester.press(button);
// await response.up();
});
await tester.pumpAndSettle();
// These all work now
expect(find.byKey(alertDialogKey), findsOneWidget);
expect(find.byIcon(Icons.catching_pokemon), findsOneWidget);
// Still doesn't work, so I'll check for data in the AlertDialog:
// expect(
// find.byElementType(AlertDialog, skipOffstage: false), findsOneWidget);
},
);
}
void main() {
// Set to false to run app so you can interact
const runTest = true;
if (runTest) {
mainTest();
} else {
runApp(MyApp());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment