Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Widget Tests with NetworkImage

Tags:

flutter

dart

I have a Widget with NetworkImage (so far with hard-coded url).
I would like to widget test this Widget, but I got 404 when I run widget test (url is 100% valid).
How can I make NetworkImages load themselves or (which would be better) ignore them so that my tests won't fail because of 404?

like image 380
Marcin Szałek Avatar asked Mar 08 '18 05:03

Marcin Szałek


People also ask

What types of tests can you perform in flutter?

Once the app is complete, you will write the following tests: Unit tests to validate the add and remove operations. Widgets tests for the home and favorites pages. UI and performance tests for the entire app using integration tests.

What is pump widget in flutter?

pumpWidget method Null safetyRenders the UI from the given widget . Calls runApp with the given widget, then triggers a frame and flushes microtasks, by calling pump with the same duration (if any). The supplied EnginePhase is the final phase reached during the pump pass; if not supplied, the whole pass is executed.


1 Answers

In widget tests, the default HTTP client has been replaced with one that always returns 400s. There's a sample on how to do this in the flutter_markdown repo along with couple other places. I used to copy and paste this to every project, but I did it enough times to get quite bored.

There's now a library for this (by me), called "image_test_utils". You can wrap your widget tests with a provideMockedNetworkImages method, which replaces the mocked HTTP client with one that always returns transparent images. Which in turn makes your tests pass.

pubspec.yaml:

dev_dependencies:
  image_test_utils: ^1.0.0

my_image_test.dart:

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:image_test_utils/image_test_utils.dart';

void main() {
  testWidgets('my image test', (WidgetTester tester) async {
    provideMockedNetworkImages(() async {
      /// Now we can pump NetworkImages without crashing our tests. Yay!
      await tester.pumpWidget(
        MaterialApp(
          home: Image.network('https://example.com/image.png'),
        ),
      );

      /// No crashes.
    });
  });
}
like image 158
Iiro Krankka Avatar answered Oct 10 '22 03:10

Iiro Krankka