mono0926 / image_test_utils

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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.

License:BSD 2-Clause "Simplified" License


Languages

Language:Dart 79.5%Language:Java 10.7%Language:Objective-C 9.8%