Chloé
Chloé

Reputation: 1139

Testing Widget with ChangeNotifierProvider

I do not understand how widget tests works with ChangeNotifier Provider despite all tutorials. I am beginner.

Here is the widget I need to test.

class SummaryScreen extends StatelessWidget {   
const SummaryScreen({Key? key}) : super(key: key);

@override   
Widget build(BuildContext context) {

    List<Person> tenants = context.watch<TenantSTATE>().tenants;

    return Scaffold( 
       body: Text(tenants.length) 
    );
    }

Here is my test :

void main() async {

  testWidgets("Flutter Widget Test", (WidgetTester tester) async {

    await tester.pumpWidget(SummaryScreen());
    expect(find.widgetWithIcon(FloatingActionButton, Icons.add), findsOneWidget);

  });
}

I am getting this error :

Could not find the correct Provider above this SummaryScreen Widget

What should I do ?

Upvotes: 1

Views: 1040

Answers (1)

user18309290
user18309290

Reputation: 8380

Add needed providers to the widget tree when calling pumpWidget, like you do it in your app, something like this:

await tester.pumpWidget(
  MultiProvider(
    providers: [
      Provider<Something>(create: (_) => Something()),
      Provider<SomethingElse>(create: (_) => SomethingElse()),
      Provider<AnotherThing>(create: (_) => AnotherThing()),
    ],
    child: SummaryScreen(),
  )
)

Upvotes: 1

Related Questions