Sub topic 15
Testing a Form with Widget Tests
Assume you know basic Dart, nullable types, closures, Flutter widgets, StatefulWidget, and layouts such as Column and Scaffold. This chapter shows how to test a form's behavior instead of checking its private implementation.
A widget test builds a small Flutter widget tree in a test environment. It can find widgets, enter text, tap buttons, and check what appears on screen. This makes it useful for verifying the user-visible validation flow.
Test the user journey
A useful form test follows the same steps as a user:
- Build the form.
- Tap submit while the field is empty.
- Check that the validation message appears.
- Enter valid text.
- Submit again.
- Check that the validation message disappears.
Give important widgets keys when text labels might change or appear more than once. Keys make tests less dependent on the visual wording.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class SignUpForm extends StatefulWidget {
const SignUpForm({super.key});
@override
State<SignUpForm> createState() => _SignUpFormState();
}
class _SignUpFormState extends State<SignUpForm> {
final _formKey = GlobalKey<FormState>();
final _emailController = TextEditingController();
@override
void dispose() {
_emailController.dispose();
super.dispose();
}
String? _validateEmail(String? value) {
if (value == null || value.trim().isEmpty) {
return 'Email is required';
}
if (!value.contains('@')) {
return 'Enter a valid email address';
}
return null;
}
void _submit() {
if (_formKey.currentState!.validate()) {
debugPrint('Submitted ${_emailController.text}');
}
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: [
TextFormField(
key: const Key('emailField'),
controller: _emailController,
decoration: const InputDecoration(labelText: 'Email'),
validator: _validateEmail,
),
ElevatedButton(
key: const Key('submitButton'),
onPressed: _submit,
child: const Text('Sign up'),
),
],
),
);
}
}
void main() {
testWidgets('validates and then accepts an email', (tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(body: SignUpForm()),
),
);
await tester.tap(find.byKey(const Key('submitButton')));
await tester.pump();
expect(find.text('Email is required'), findsOneWidget);
await tester.enterText(
find.byKey(const Key('emailField')),
'[email protected]',
);
await tester.tap(find.byKey(const Key('submitButton')));
await tester.pump();
expect(find.text('Email is required'), findsNothing);
expect(find.text('Enter a valid email address'), findsNothing);
});
}pumpWidget creates the test application. tap simulates a tap. enterText replaces the current field value. pump lets Flutter process the resulting state change and rebuild the widgets.
Check invalid values separately
Each validation rule should have a focused test. For example, enter not-an-email, submit, and expect Enter a valid email address. A separate test can verify that a valid address produces no error.
Use findsOneWidget when exactly one matching widget should exist. Use findsNothing when an error should be absent. These assertions describe behavior that matters to a user.
Understand the test sequence
Run the test with flutter test. If the form performs asynchronous work, use await tester.pump() after the action that starts it. Use pumpAndSettle() only when all expected animations and asynchronous rebuilds should finish.
Exercise
Why should a widget test call pump after tapping the submit button?
Show answer
The tap changes form state, and pump lets Flutter rebuild the widget tree before the test searches for the updated error message.