简体   繁体   中英

Write flutter widget tests that uses GoogleFonts

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);
});

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.

在此处输入图像描述 First you have to provide the font in pubspec.yaml file Just follow those step Download the fort extract it. Go to your project file and create a folder name it "assets" and inside assets folder create another folder called "fonts". In this fonts folder paste the font.tiff copy the file name in this case it is"MajorMonoDisplay-Regular.ttf"

Next you have to provide the font information in pubspec.yaml file just copy paste those code.

  fonts:
- family: MajorMonoDisplay
  fonts:
    - asset: assets/fonts/MajorMonoDisplay-Regular.ttf

Next in open terminal run "flutter pub get" and now just provide the fort family in your TextStyle. Example:

child: Column(
              children: [
                Text(
                  'Should display _now text',
                  style: TextStyle(
                    fontSize: 20,
                    fontFamily: 'MajorMonoDisplay',
                  ),
                )
              ],
            ),

If the front is not showing then close the app and rerun it.

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