3

I'm new to Flutter testing and was hoping If you could help me. I've a class called AddShimmer that looks like this ->

AddShimmer(
          child: ListTile(
            title: buildLoadingAnimation(context),
          ),
        ),

Now, I'm trying to write a flutter test just to check if a child widget is being passed to the AddShimmer class. To do that, I'm writing something like this ->

testWidgets('Shimmer has a child widget', (WidgetTester tester) async {
    const childWidget = ListTile(
      title: Text('Loading'),
    );
    await tester.pumpWidget(
     const AddShimmer(child: childWidget)
    );
    expect(find.byWidget(childWidget), findsOneWidget);
  });

While I'm executing the test, I'm getting an exception which says ->

The following assertion was thrown building ListTile(dirty):
No Directionality widget found.
ListTile widgets require a Directionality widget ancestor.
The specific widget that could not find a Directionality ancestor was:
  ListTile

What does it mean and how to test this out ??

Divyam Dhadwal
  • 395
  • 3
  • 19

1 Answers1

2

Basically flutter needs some additional context in order to render the widget. I usually just wrap it in a Scaffold inside a MaterialApp.

await tester.pumpWidget(
  const MaterialApp(
    home: Scaffold(
      body: AddShimmer(child: childWidget),
    ),
  ),
);
mmcdon20
  • 5,767
  • 1
  • 18
  • 26
  • Got it! DO i need to do this for every test case that I write ?? I mean for all the widgets out there ? All wrapped within the Scaffold and material app? – Divyam Dhadwal Dec 20 '21 at 05:00
  • Some basic widgets like `await tester.pumpWidget(Container());` don't seem to need the additional context. Also, if the widget already has a `MaterialApp` and `Scaffold` inside it, it would not need to be wrapped inside another `MaterialApp` and `Scaffold`. So it depends. – mmcdon20 Dec 20 '21 at 05:06
  • Alright. Thanks for the help :) Really appreciate it. – Divyam Dhadwal Dec 20 '21 at 05:07
  • I should note that you could instead wrap `AddShimmer(child: childWidget)` in a `Directionality` widget, as the error message suggests, but then you will get another error saying it needs to be inside a `Material` widget, and then inside a `MediaQuery` and so on. Wrapping in a `MaterialApp` and `Scaffold` just happens to be easier in my experience. – mmcdon20 Dec 20 '21 at 05:21