Testing Widgets with Flutter. Basics.

David Leybovich
2 min readMar 26, 2019

--

It’s not a secret that unit testing is allowing you to develop quality applications faster, but it’s not always easy to remove logic from UI.

Testing Widgets with Flutter

An excellent way to deal with this would be testing the UI in a unit-testing fashion. In Android, we have Roboelectric — which is super useful. In Flutter the widget testing is baked to the platform and comes out of the box.

A common widget test might look somewhat like this:

testWidgets('great widget test', (tester) async {await tester.pumpWidget(new MyWidget());final finder = find...expect(finder, findsOneWidget);
}

You pump your widget; then you find if the widget contains the text/image/icon/button and confirm if it appears correctly.

Apply widget changes

One important note to mention is that sometimes you change your widget depending on a user action. For instance: remove a todo field when the user taps the delete button.

await tester.tap(find.byType(Checkbox));// Rebuild the Widget after the state has changed
await tester.pump();

This is valid only if you change the state of the widget and you need to rebuild it. It will not help you find out if the button callback was invoked.

Finder options

You can find the target widget by a bunch of ways:

  • type finder.byType
  • key finder.byKey
  • text finder.textfinder.widgetWithText
  • icon finder.byIcon
  • create a duplicate widget in your test finder.byWidget
  • regex finder.bySemanticsLabel
  • And so on… finder.ancestorfinder.descendant

A great way to learn how to find widgets is to take a look at the source code. I’m also sure the API might change and extend by the time you read this article. https://github.com/flutter/flutter/blob/master/packages/flutter_test/lib/src/finders.dart

Conclusion

Testing widgets in Flutter is almost as easy as testing pure Dart code. The fact that the developers thought about it and created such a powerful test API is fantastic.

--

--