dartflutter

Flutter Widget Tests with NetworkImage


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?


Solution

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