Sub topic 3
Tapping, entering text and pumping frames
This chapter assumes you know Dart's async and await, can write stateful widgets, use the flutter command, and add packages in pubspec.yaml.
Tapping and pumping frames
tester.tap sends a press to a widget, but the screen does not redraw until you call tester.pump(). Use pumpAndSettle() to advance frames until all animations finish.
testWidgets('tap increments the counter', (tester) async {
await tester.pumpWidget(const MaterialApp(home: CounterPage()));
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
expect(find.text('1'), findsOneWidget);
});Testing widgets that depend on services
Pass services into a widget through its constructor. In a test, give the widget a mocktail mock and stub the answer it returns.
class MockUserRepository extends Mock implements UserRepository {}
final repository = MockUserRepository();
when(() => repository.fetchName(1)).thenAnswer((_) async => 'Ada');Golden tests
A golden test compares a rendered widget with a stored PNG. Run flutter test --update-goldens to create or refresh the image.
testWidgets('CounterPage matches golden', (tester) async {
await tester.pumpWidget(const MaterialApp(home: CounterPage()));
await expectLater(
find.byType(CounterPage),
matchesGoldenFile('goldens/counter_page.png'),
);
});Integration tests
Integration tests run the full app on a device or emulator. Put them in the integration_test/ folder, add the integration_test package to dev_dependencies, and run flutter test integration_test.
Code coverage
flutter test --coverage writes line coverage data to coverage/lcov.info.
Continuous integration
In your CI pipeline, run flutter test --coverage as a build step. The job fails when any test fails.
Exercise
A widget test taps a button, but the expected text never appears. Which call did you probably forget, and what does it do?
Show answer
Call tester.pump() after the tap. It processes a frame so the widget rebuilds. Use pumpAndSettle() if the widget runs an animation.