Luke
Luke

Reputation: 1679

Widget testing TextFormField obscureText value

I cannot seem to find a way to widget test whether a TextFormField has obscureText set true or false.

I know that TextFormField is a wrapper around TextField, and obscureText is a property of TextField, but cannot think of a way to access obscureText within my test.

So, when I try to access obscureText I get the message: The getter 'obscureText' isn't defined for the type 'TextFormField'

Anyone know how to test obscureText property for a TextFormField?

  testWidgets(
    'show and hide password fields',
    (
      WidgetTester tester,
    ) async {
      await tester.pumpWidget(
        materialWrapper(
          child: emailSignUpScreen,
        ),
      );
      final Finder passwordTextFormField = find.byKey(
        const Key(
          'passwordTextFormField',
        ),
      );
      final TextFormField input =
          tester.widget<TextFormField>(passwordTextFormField);
      expect(input.obscureText, true);
    },
  );

Upvotes: 4

Views: 1510

Answers (2)

Sanjay Bharwani
Sanjay Bharwani

Reputation: 4839

Below is a test to verify the obscure property each time show / hide password icon is toggled.

patrolWidgetTest('verify show & hide password', ($) async {
      const loginPage = LoginPage();
      await $.pumpWidgetAndSettle(
      wrapWithApp(
      child: loginPage
      ),
      );
      final passwordField = $(Key('passwordTextField'));
      final showPasswordIcon = $(IconButton).$(Icons.visibility);
      final hidePasswordIcon = $(IconButton).$(Icons.visibility_off);
      
      
      expect(showPasswordIcon, findsOneWidget);
      expect(hidePasswordIcon, findsNothing);
      expect($.tester.firstWidget<TextField>(passwordField).obscureText, true);
      
      await showPasswordIcon.tap();
      
      expect(hidePasswordIcon, findsOneWidget);
      expect(showPasswordIcon, findsNothing);
      expect($.tester.firstWidget<TextField>(passwordField).obscureText, false);
      
      await hidePasswordIcon.tap();
      
      expect(showPasswordIcon, findsOneWidget);
      expect(hidePasswordIcon, findsNothing);
      expect($.tester.firstWidget<TextField>(passwordField).obscureText, true);

}

Upvotes: 0

Tomek Polański
Tomek Polański

Reputation: 1763

TextFormField uses EditableText to obscure it, you can just do:

final passwordTextFormField = find.descendant(
  of: find.byKey(const Key('passwordTextFormField')),
  matching: find.byType(EditableText),
);
final input = tester.widget<EditableText>(passwordTextFormField);
expect(input.obscureText, isTrue);

Upvotes: 8

Related Questions