Reputation: 6157
what I'm trying to test is: the user taps a button and the snackbar is shown for five second.
Here is the scaffold with its key:
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>(debugLabel: "scaffoldState");
...
builder: (context, viewModel) => Scaffold(
key: _scaffoldKey,
Then the code for the button and the snackBar:
child: FlatButton(key: Key('loginButton'), onPressed: () {
validate();
...
validate() {
// FormState object can be used to save, reset, and validate
// every FormField that is a descendant of the associated Form.
final FormState form = _formKey.currentState;
if (form.validate()) {
form.save();
form.reset();
//implementation of the snackBar:
_scaffoldKey.currentState.showSnackBar(new SnackBar(
duration: new Duration(seconds: 5)
...
And I am trying to test this behaviour in this way (I'm using also Flutter redux):
void main(){
final store = Store<AppState>(reducer, initialState: AppState.initialState());
testWidgets("MaterialApp local", (WidgetTester tester) async{
await tester.pumpWidget(new StoreProvider(
store: store,
child: MaterialApp(
home: LoginView(),
)));
await tester.pumpAndSettle();
await tester.press(find.byKey(Key("loginButton")));
expect();
I don't know what to put inside expect. I was trying to take the GlobalKey using find.ByKey(Key)) and to search for the debugLabel, but it doesn't seem to work. I'm trying since 2 days, but I can't find a way out.
Upvotes: 3
Views: 2366
Reputation: 3467
It might be a little late to answer this, but since it was the second result on Google when typing "Flutter test Snackbar", I will just give my two cents:
It's actually pretty simple. Don't think of the Snackbar as being something completely different only because it only resides at the bottom for a few seconds. Lastly, the Snackbar is just another Widget.
Keeping this in mind you can test it as follows:
testWidgets("MaterialApp local", (WidgetTester tester) async{
...
// Test if the Snackbar appears
expect(find.byType(SnackBar), findsOneWidget);
// Test if it contains your text
expect(find.text('TAPS!'), findsOneWidget);
});
Upvotes: 1
Reputation: 1
i actually met the same condition as you did, and all i did is put a text as the content of the snackbar.
for showing the snackbar, the code i use is
scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("TAPS!"),));
}, "SEE ALL", backgroundColor: Colors.red, textColor: Colors.blue)
and i expect to find a text with the same content as i put in, and add findsOneWidget.
expect(find.text("TAPS!"), findsOneWidget);
Upvotes: 0