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);
});
}
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);
});
}