Sub topic 15
Testing a Form with Widget Tests
A widget test builds a widget tree in a headless test environment, lets you type into it and tap it, and checks what it renders. For forms this is the most useful kind of test. It exercises the Form, the validator functions, and the visible error text together, without a device or emulator.
Prerequisites
This chapter assumes you have:
- A working
FormwithTextFormFieldvalidators and aGlobalKey<FormState>, as built in earlier chapters. - Basic
flutter_testknowledge:testWidgets,find, andexpect. - Comfort with
asyncandawaitin Dart.
The tests import the app code through its package name. Replace your_app with the name: in your pubspec.yaml.
The working model
Three ideas explain most widget-test behavior.
- Nothing happens until you pump.
tester.pumpWidgetbuilds the first frame. After any action that changes state, such asenterTextortap, the UI is stale until you calltester.pump(), which runs one frame. Callingvalidate()marks fields as having errors, but the error text only appears after the next frame. - Finders locate widgets, matchers judge them.
find.text('Email is required')returns a finder.expect(finder, findsOneWidget)fails if there are zero or several matches. - The tester acts like a user.
enterTextsends text to the field's editing state.tapdispatches a pointer event at the widget's center, so the widget must be on screen and not covered.
A reusable harness
Form fields need a Material ancestor for ink and decoration, and a MediaQuery for layout. MaterialApp plus Scaffold supplies both. Wrap that in a helper so each test stays short.
A testable form
The SignUpForm from earlier chapters only prints on success, so a test cannot observe a successful submit. A form that reports its result through a callback is easier to test. This one also uses cross-field validation:
import 'package:flutter/material.dart';
class SetPasswordForm extends StatefulWidget {
const SetPasswordForm({super.key, required this.onSubmit});
final ValueChanged<String> onSubmit;
@override
State<SetPasswordForm> createState() => _SetPasswordFormState();
}
class _SetPasswordFormState extends State<SetPasswordForm> {
final _formKey = GlobalKey<FormState>();
final _password = TextEditingController();
final _confirm = TextEditingController();
@override
void dispose() {
_password.dispose();
_confirm.dispose();
super.dispose();
}
void _submit() {
if (_formKey.currentState!.validate()) {
widget.onSubmit(_password.text);
}
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: [
TextFormField(
key: const Key('password'),
controller: _password,
obscureText: true,
decoration: const InputDecoration(labelText: 'Password'),
validator: (value) => (value ?? '').length < 8
? 'Use at least 8 characters'
: null,
),
TextFormField(
key: const Key('confirm'),
controller: _confirm,
obscureText: true,
decoration: const InputDecoration(labelText: 'Confirm password'),
validator: (value) =>
value != _password.text ? 'Passwords do not match' : null,
),
ElevatedButton(onPressed: _submit, child: const Text('Save')),
],
),
);
}
}The Key values give the tests a stable way to find each field. Finding by label text is fragile, because a label can also appear in a hint or in an error message.
Testing the failure and success paths
The tests below cover three outcomes: a field-level error, a cross-field error, and a successful submit. Each one also checks that onSubmit fires or does not fire.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:your_app/set_password_form.dart';
Future<void> pumpForm(
WidgetTester tester,
ValueChanged<String> onSubmit,
) {
return tester.pumpWidget(
MaterialApp(
home: Scaffold(body: SetPasswordForm(onSubmit: onSubmit)),
),
);
}
void main() {
group('SetPasswordForm', () {
testWidgets('rejects a short password', (tester) async {
final submitted = <String>[];
await pumpForm(tester, submitted.add);
await tester.tap(find.text('Save'));
await tester.pump();
expect(find.text('Use at least 8 characters'), findsOneWidget);
expect(submitted, isEmpty);
});
testWidgets('rejects mismatched passwords', (tester) async {
final submitted = <String>[];
await pumpForm(tester, submitted.add);
await tester.enterText(find.byKey(const Key('password')), 'longenough');
await tester.enterText(find.byKey(const Key('confirm')), 'different1');
await tester.tap(find.text('Save'));
await tester.pump();
expect(find.text('Passwords do not match'), findsOneWidget);
expect(find.text('Use at least 8 characters'), findsNothing);
expect(submitted, isEmpty);
});
testWidgets('submits when both fields are valid', (tester) async {
final submitted = <String>[];
await pumpForm(tester, submitted.add);
await tester.enterText(find.byKey(const Key('password')), 'longenough');
await tester.enterText(find.byKey(const Key('confirm')), 'longenough');
await tester.tap(find.text('Save'));
await tester.pump();
expect(find.text('Passwords do not match'), findsNothing);
expect(submitted, ['longenough']);
});
});
}Passing submitted.add as the callback records every call in a list. That lets you assert both how many times the form submitted and what value it sent.
Some details about these tests:
- The first test never calls
enterText. Both fields are empty, so only the password rule fails. The confirm field passes because'' == ''. - The text of obscured fields is not in the tree as plain text, so
find.text('longenough')finds nothing. Assert on the callback value or oncontroller.textinstead. - Each
testWidgetscall gets a fresh tree, so state never leaks between tests.
Testing validation timing
AutovalidateMode changes when errors appear, so it deserves its own test. With AutovalidateMode.onUserInteraction, as in SignUpForm, an error appears after typing, before any submit:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:your_app/sign_up_form.dart';
void main() {
testWidgets('validates on interaction before any submit', (tester) async {
await tester.pumpWidget(
const MaterialApp(home: Scaffold(body: SignUpForm())),
);
expect(find.text('Enter a valid email address'), findsNothing);
await tester.enterText(find.byType(TextFormField), 'not-an-email');
await tester.pump();
expect(find.text('Enter a valid email address'), findsOneWidget);
});
}The first expect matters as much as the second. It proves the form starts clean. A form that shows errors before the user touches anything is a common regression when someone changes autovalidateMode.
Pump variants
| Call | What it does | Use it when |
|---|---|---|
| `pump()` | Runs one frame | After `enterText`, `tap`, or a `setState` |
| `pump(Duration)` | Advances the fake clock, then runs a frame | A validator or submit handler awaits a `Future.delayed` |
| `pumpAndSettle()` | Pumps frames until none are scheduled | Navigation, dialogs, or animations that end |
pumpAndSettle times out if something animates forever, such as a CircularProgressIndicator shown while a submit is in flight. In that case, pump a fixed duration and assert on the spinner.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Expected one widget, found none, right after a tap | No `pump()` after the tap | Add `await tester.pump()` |
| `No Material widget found` or a `MediaQuery` error | The field was pumped without `MaterialApp` and `Scaffold` | Use the harness helper |
| Found more than one matching widget | The same text appears twice, such as in a label and in a hint | Use `find.byKey` or narrow with `find.descendant` |
| Tap has no effect, with a "would not hit test" warning | The button is off screen or covered | Call `await tester.ensureVisible(finder)` first |
| `A Timer is still pending` at the end of the test | Code used `Future.delayed` and the test never advanced the clock | `await tester.pump(const Duration(seconds: 1))` |
| `find.text` cannot see typed text | The field uses `obscureText` | Assert on the controller or the callback |
Testing server-side errors
Server errors arrive after an await. In a test, replace the network call with a fake that returns a Future, such as Future.value('Email already taken'). Tap submit, then await tester.pump() so the future completes, and pump once more to rebuild. Then assert on the message. If the fake uses Future.delayed, pass the same duration to pump(Duration).
What to cover
A short checklist for each form:
- The initial state shows no errors.
- Each validator rule has one failing input that produces its exact message.
- A fully valid submit calls the callback once with the expected value.
- An invalid submit never calls the callback.
- Any timing mode, such as
onUserInteraction, is checked before and after interaction.
Exercise
A test enters 'abc' into an email field with a validator, taps the submit button, and immediately runs expect(find.text('Enter a valid email address'), findsOneWidget). It fails with zero matches, though the app works when run by hand. What is missing, and why?
Show answer
The test needs await tester.pump() between the tap and the expect. validate() runs during the tap, but the error text is only built in the next frame. Without a pump, the widget tree still shows the old state.
Exercise
Write a test for SetPasswordForm that enters a valid password and a matching confirmation, taps Save, and checks that onSubmit was called exactly once. Which object do you use to record the calls?
Show answer
Use a list, for example final submitted = <String>[];, and pass submitted.add as onSubmit. After enterText on both keys, tap(find.text('Save')), and pump(), assert expect(submitted, ['longenough']);. The list's length confirms one call, and its content confirms the value.