Write flutter widget tests that uses GoogleFonts

Issue

I need to write a flutter widget test to test a widget with GoogleFonts plugin in use. However, it gives network failer which is correct as the test suit doesn’t have access to the internet. The problem is GoogleFonts.majorMonoDisplayTextTheme is a static method which makes it impossible to mock the GoogleFont class when using in the widget test.

Error: google_fonts was unable to load font MajorMonoDisplay-Regular because the following exception occurred: 
Exception: Failed to load font with URL: https://fonts.gstatic.com/s/a/9901077f5681d4ec7e01e0ebe4bd61ba47669c64a7aedea472cd94fe1175751b.ttf

Widget usage:

 Container(
      padding: EdgeInsets.only(top: 10),
      child: Text(
        _now,
        style: GoogleFonts.majorMonoDisplayTextTheme(Theme.of(context).textTheme).headline3,
      ),
    ),

Widget test method:

testWidgets(
  'Shoudl display _now text',
  (WidgetTester tester) async {
  await tester.pumpWidget(_TestWidgetWithGoogleFont);
  await tester.pumpAndSettle();
  expect(find.byType(Text), findsOneWidget);
});

Solution

There is another way to silence the error. Especially handy if you don’t want to (or can’t) add additional files to a project.

Simply add this line of code to a desired test:

setUp(() => GoogleFonts.config.allowRuntimeFetching = false);

This code disallows runtime fetching which is a process that raises the erorr in the first place.

Answered By – Ilia Kurtov

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

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