How to write a simple test for a Snack Bar in Flutter?

1,328

Have you wrapped your test widget in a Scaffold? SnackBars can only be shown if a Scaffold is an ancestor of the widget that calls the SnackBar.

Example:

void main() {
  testWidgets('SnackBar control test', (WidgetTester tester) async {
    const String helloSnackBar = 'Hello SnackBar';
    const Key tapTarget = Key('tap-target');
    await tester.pumpWidget(MaterialApp(
      home: Scaffold(
        body: Builder(
          builder: (BuildContext context) {
            return GestureDetector(
              onTap: () {
                Scaffold.of(context).showSnackBar(const SnackBar(
                  content: Text(helloSnackBar),
                  duration: Duration(seconds: 2),
                ));
              },
              behavior: HitTestBehavior.opaque,
              child: Container(
                height: 100.0,
                width: 100.0,
                key: tapTarget,
              ),
            );
          }
        ),
      ),
    ));
    expect(find.text(helloSnackBar), findsNothing);
    await tester.tap(find.byKey(tapTarget));
    expect(find.text(helloSnackBar), findsNothing);
    await tester.pump(); // schedule animation
    expect(find.text(helloSnackBar), findsOneWidget);
  });

From: https://github.com/flutter/flutter/blob/master/packages/flutter/test/material/snack_bar_test.dart

Share:
1,328
TheBranch
Author by

TheBranch

Updated on December 20, 2022

Comments

  • TheBranch
    TheBranch over 1 year

    I'm surprised no one seems to have asked this before, which means the answer might be obvious, but I have a screen with a text field and a button. The user enters their email in the text field. Then presses the button to see if the email is in the database. The program then displays a snackbar with 'success' text or 'fail' text (2 second duration).

    Here is my code (5 lines):

    await driver.enterText(field, '[email protected]');
    
    var btn = find.widgetWithText(RaisedButton, 'SEND MY PASSWORD');
    
    await driver.tap(btn);
    
    await driver.pump();
    
    expect(find.text( 'E-mail address not found!'), findsOneWidget);
    

    When I use the app in the emulator, everything is fine but in the test the last line throws an error saying that it cannot find the matching widget. What am I missing?