How to do a Flutter Test for a widget that accesses Provider.of(context)

Issue

I was wondering if someone could help me out, I am having trouble writing tests for my home page on my flutter project as it relies on a Provider.

home_page.dart

Future<NewsModel> newsData = Provider.of<Future<NewsModel>>(context);

return FutureProvider(
  create: (context) => newsData,
  child: (newsData != null)
      ? Scaffold(
          body: SmartRefresher(
            controller: _refreshController,
            onRefresh: _refreshNews,
            onLoading: _onLoading,
            child: Consumer<NewsModel>(
              builder: (_, news, __) {...}

main.dart

return MultiProvider(
  providers: [
    FutureProvider(create: (context) => geolocatorService.getlocation()),
    ProxyProvider<Position, Future<NewsModel>>(
      update: (context, position, news) {
        return (position != null) ? newsService.getNews() : null;
      },
    ),

home_page_test.dart

testWidgets('Test the home screen', (WidgetTester tester) async {
HomePage homePage = new HomePage();

await tester.pumpWidget(
  makeWidgetTestable(
    child: homePage,
  ),
);

});
}

When I run this test I receive the below error, I am really confused here and need some guidance. I am fairly experienced with Flutter but am a newbie to writing widget tests for widgets that require external dependencies. If someone can help this would be great.

Error:

The following ProviderNotFoundException was thrown building HomePage(dirty, dependencies [MediaQuery], state: _HomePageState#ce244): Error: Could not find the correct Provider<Future<NewsModel>> above this HomePage Widget

Solution

If you wrap the following code with the provider from your main file:

await tester.pumpWidget(
  makeWidgetTestable(
    child: homePage,
  ),
);

and turn it into:

testWidgets('Test the home screen', (WidgetTester tester) async {
//No longer need the following line
//HomePage homePage = new HomePage();

await tester.pumpWidget(
MultiProvider(
  providers: [
    FutureProvider(create: (context) => geolocatorService.getlocation()),
    ProxyProvider<Position, Future<NewsModel>>(
      update: (context, position, news) {
        return (position != null) ? newsService.getNews() : null;
      },
    ),
    child: homePage,
  ),
);

Answered By – Donald Smith

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *