5

Im trying to test if password its obscured, this is how far I go, but seems like flutter can read a text even if it is obscured.

 testWidgets('password must be hidden', (WidgetTester tester) async {
  await tester.pumpWidget(wrapWithMaterialApp(child: page));

  await tester.enterText(find.byKey(Key('pass')), '1234');
  final passFinder = find.text('1234');
  expect(passFinder, findsNothing);

});

the test actually find '1234' but im completely sure its obscured.

1 Answers1

8

Regardless of obscureText flag, entered text is always stored in memory (this parameter affects only visual representation). In tests we can only check this property as follows:

  testWidgets('TextField', (WidgetTester tester) async {
    await tester.pumpWidget(MyApp());
    final finder = find.byKey(Key('pass'));
    final input = tester.firstWidget<TextField>(finder);
    expect(input.obscureText, true);
  });

Testing TextFormField requires additional effort (TextField is child of TextFormField):

  testWidgets('TextFormField', (WidgetTester tester) async {
    await tester.pumpWidget(MyApp());
    final finder = find.descendant(
      of: find.byKey(Key('pass')),
      matching: find.byType(TextField),
    );
    final field = tester.firstWidget<TextField>(finder);
    expect(field.obscureText, true);
  });
Spatz
  • 18,640
  • 7
  • 62
  • 66
  • Can we achieve the same with TextFormField doesn't seem like there is "obscureText" accessible with tester.firstWidget – ahmetakil Mar 10 '23 at 13:50
  • @ahmetakil `TextFormField` encapsulates `TextField` as child component, hence we should use `find.descendant`. – Spatz Mar 12 '23 at 10:23