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);
});
}
The navigation drawer is added using the Drawer widget. It can be opened via swipe gesture or by clicking on the menu icon in the app bar. Typically, the navigation drawer opens up from the left side of the screen, but you can also configure it to open from the right side (for the LTR text settings).
You can simply use onDrawerChanged for detecting if the drawer is opened or closed in the Scaffold widget.
To close the drawer, use either ScaffoldState. closeDrawer, Navigator. pop or press the escape key on the keyboard. To disable the drawer edge swipe on mobile, set the Scaffold.
You're calling tap()
on the Drawer
, but it isn't in view as it's hidden on the left. Because of this, the Finder
doesn't find any elements and the tap()
is unsuccessful. And even if the Finder
found the Drawer
, tapping on the Drawer
itself doesn't open it anyway.
One way, and in my opinion, the simplest way of doing it is to provide a GlobalKey
for the Scaffold
and call openDrawer()
on the current State
of it. You could also tap on the hamburger icon or swipe from the left - but calling openDrawer()
is more deterministic:
void main() {
testWidgets('my drawer test', (WidgetTester tester) async {
final scaffoldKey = GlobalKey<ScaffoldState>();
const displayName = "displayName";
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
key: scaffoldKey,
drawer: const Text(displayName),
),
),
);
scaffoldKey.currentState.openDrawer();
await tester.pump();
expect(find.text(displayName), findsOneWidget);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With