'How to open a drawer in flutter test
I am trying to test a custom drawer but find it hard opening it in the test, tried the following to begin with and even this test doesn't pass. The error is: Bad state: no element.
void main() {
testWidgets('my drawer test', (WidgetTester tester) async {
final displayName = "displayName";
var drawKey = UniqueKey();
await tester.pumpWidget(MaterialApp(
home: Scaffold(
drawer: Drawer(key: drawKey, child: Text(displayName),),
)));
await tester.tap(find.byKey(drawKey));
expect(find.text(displayName), findsOneWidget);
});
}
Solution 1:[1]
You can grab the top left of the parent widget and use dragFrom in order to simulate opening the drawer. In comparison to the current accepted answer, this does not require you to pass the scaffold key.
An example with a slight modification of the original code:
testWidgets('my drawer test', (WidgetTester tester) async {
final displayName = "displayName";
var drawKey = UniqueKey();
await tester.pumpWidget(MaterialApp(
home: Scaffold(
drawer: Drawer(key: drawKey, child: Text(displayName),),
)));
await tester.dragFrom(tester.getTopLeft(find.byType(MaterialApp)), Offset(300, 0));
await tester.pumpAndSettle();
expect(find.text(displayName), findsOneWidget);
});
Notice tester.pumpAndSettle() was added to ensure enough time has passed.
Solution 2:[2]
another solution:
final ScaffoldState state = tester.firstState(find.byType(Scaffold));
state.openDrawer();
await tester.pump();
await tester.tap(find.byTooltip('your tooltip text'));
await tester.pump();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TheBeardedOne |
| Solution 2 | Gülsen Keskin |
