Skip to content

Provide mocked responses for Image.network widgets in Flutter widget tests.

License

Notifications You must be signed in to change notification settings

roughike/image_test_utils

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

image_test_utils

pub package Build Status

Without providing mocked responses, any widget test that pumps up Image.network widgets will crash.

There's a blog post that goes more into detail on this.

Copy-pasting the code for mocking the image responses to every new project gets a little boring. This helper library makes it easier to provide those mocked image responses.

Usage

First, depend on the library:

pubspec.yaml

dev_dependencies:
  image_test_utils: ^1.0.0

Note that this library should be included in your dev_dependencies block; not in your regular dependencies.

In your widget tests, import the library and wrap your widget test in a provideMockedNetworkImages method.

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

void main() {
  testWidgets('should not crash', (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'),
        ),
      );
      
      /// Other test code goes here.
    });
  });
}

All HTTP GET requests inside the closure of provideMockedNetworkImages will receive a mocked image response, and your tests will not crash with 404's anymore.

About

Provide mocked responses for Image.network widgets in Flutter widget tests.

Resources

License

Stars

Watchers

Forks

Packages

No packages published