Sub topic 2
Finding widgets and simulating user input
This chapter assumes you know Dart and basic Flutter, can write a widget test with flutter_test, and have integration_test set up in your project. Each step below builds on the test file that you create in the first section.
Finding widgets and simulating input
A finder searches the widget tree for widgets that match a rule. Keys are the most reliable finder. You assign a Key in your app code, and it stays the same when the text or layout changes.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:my_app/main.dart' as app;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('login form accepts input', (tester) async {
app.main();
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('email_field')), '[email protected]');
await tester.tap(find.byKey(const Key('submit_button')));
await tester.pumpAndSettle();
expect(find.text('Welcome'), findsOneWidget);
});
}find.text('Sign in') and find.byType(ElevatedButton) also work. Text finders break when copy changes, and type finders match many widgets, so prefer keys for any control the test uses.
enterText requires a widget that accepts text input, such as a TextField. tap works on any widget that responds to gestures.
Pumping frames and waiting for animations
A test does not wait for the app by itself. Flutter builds and paints frames only when the test asks it to pump them. Choose the pump call based on what the screen is doing.
| Call | What it does | Use when |
|---|---|---|
| `tester.pump()` | Draws one frame | A state change has no animation |
| `tester.pump(const Duration(milliseconds: 300))` | Advances time by a fixed amount | An animation never ends, such as a spinner |
| `tester.pumpAndSettle()` | Pumps until no frames are scheduled | Navigation and short animations |
> Hmm
Running the tests on a real device
List the connected devices, then run the test file on the device you choose.
flutter devices
flutter test integration_test/app_test.dart -d <device_id>Replace <device_id> with the id from the first command. Each run installs the app on the device and runs the test there.
Exercise
Why does the test fail if you remove pumpAndSettle after the tap?
Show answer
The expect runs before the app draws the Welcome screen, so find.text('Welcome') finds no widget. Adding pumpAndSettle lets the navigation finish first.