简体   繁体   中英

How to write widget tree test to verify tree hierarchy

I am learning Flutter and I want to write one test for my simple MyAppBarWidget . Below is my widget

class MyAppBarWidget extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: Text("My first widget"),
          ),
        ));
  }
}

I want to test widget tree hierarchy as

  • MaterialApp has Scaffold property
  • Scaffold has AppBar property
  • AppBar has title property as Text
  • title is My first widget

Any suggestion what kind of test I should write

I tried below test

void main() {
  testWidgets("verify app bar", (WidgetTester tester) async {
    await tester.pumpWidget(MyAppBarWidget());
    var byWidget = find.byType(MaterialApp);
    var text = find.text("My first widget");
    expect(byWidget, findsOneWidget);
    expect(text, findsOneWidget);
  });
}

But this test does not say that my text field is inside AppBar widget

Can someone help me how should I write test to verify this?

Thanks

I suggest not to test widget hierarchy, you will change it often and always have to adjust the test without actually knowing anything when the test fails or succeeds. It is better to test functionality, the presence of something or the absence, tap events and interaction.

You can also look into golden (screenshot) tests to ensure that screens or pages don't change.

That being said, if you really want to do this you can use

find.ancestor(find.byType(AppBar), find.text("My first widget"));

EDIT

Or with newer versions of the test library, thanks Fred Grott :

find.ancestor(of: find.byType(AppBar), matching: find.text("My first widget"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM