Flutter: How to access / inspect properties of a widget in tests?

Viewed 3900

I want to test properties of some widgets but I don't find a simple way of doing it.

Here's a simple example with a password field, how can I check that obscureText is set to true ?


import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

const darkBlue = Color.fromARGB(255, 18, 32, 47);

Future<void> main() async {
  testWidgets('Wheelio logo appear on the login screen',
      (WidgetTester tester) async {
    final Key _formKey = GlobalKey<FormState>();
    final TextEditingController passwordController = TextEditingController();
    const Key _passwordKey = Key('PASSWORD_KEY');
    final Finder passwordField = find.byKey(_passwordKey);
    await tester.pumpWidget(MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: Form(
            key: _formKey,
            child: TextFormField(
              key: _passwordKey,
              obscureText: true,
              controller: passwordController,
            ),
          ),
        ),
      ),
    ));

    await tester.pump();
    expect(passwordField, findsOneWidget);
    final TextFormField myPasswordWidget =
        tester.widget(passwordField) as TextFormField;

    //    How can I check that obscureText property is set to true ?
  });
}

4 Answers

You can use tester and find to obtain anything in the widget tree.

For example, if you want to test that a Text has the property textAlign set to TextAlign.center, you can do:

expect(
  tester.widget(find.byType(Text)),
  isA<Text>().having((t) => t.textAlign, 'textAlign', TextAlign.center),
);

You can get the widget through the Finder.

TabBar tabBar = find.byType(TabBar).evaluate().single.widget as TabBar
final passwordField = find.byKey(_passwordKey);
final input = tester.firstWidget<TextFormField>(passwordField);

The input will be your widget, so you can now check

expect(input.obscureText, true);

CommonFinders byWidgetPredicate method

final _passwordKey = GlobalKey(debugLabel: 'PASSWORD_KEY');

await tester.pumpWidget(
 // ...
);
bool isObscureTextTrue(TextFormField widget) {
  final TextField textField = widget.builder(_passwordKey.currentState);
  return textField.obscureText;
}

final finder = find.byWidgetPredicate(
  (widget) => widget is TextFormField && isObscureTextTrue(widget),
);

expect(finder, findsOneWidget);
Related