In a Flutter widget test, how can I verify a field validation error message?
I recreated your case and was able to validate the inline error message. The idea is to add a delay of 1 second before we could test assertion. Here's what I did:
main.dart
code to display textformfield
and validate Email upon tapping Send
button:
TextFormField( decoration: new InputDecoration(hintText: 'Email ID'), keyboardType: TextInputType.emailAddress, maxLength: 32, validator: validateEmail, onSaved: (String val) { email = val; }),
validateEmail
method snippet:
if (value.length == 0) { return "Email is Required"; } else if(!regExp.hasMatch(value)){ return "Invalid Email"; }else { return null; }
Widget test to validate the inline error message for email field:
void main() { testWidgets('validate email inline error message', (WidgetTester tester) async { await tester.pumpWidget(MyApp()); final buttonFinder = find.text('Send'); final emailErrorFinder = find.text('Email is Required'); await tester.tap(buttonFinder); print('button tapped'); await tester.pump(const Duration(milliseconds: 100)); // add delay expect(emailErrorFinder, findsOneWidget); print('validated email inline error'); });}
Test result:
Hope this answers your question.