I've been trying to write a simple test for FadeInImage but with no luck. I just want to test if kTransparentImage appears as a placeholder. Then after a certain wait time (default 700ms), the URL image appears and kTransparentImage disappears.
First we'll need to use an HttpClient in order to display network image. I use nock, but feel free to use your own.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:transparent_image/transparent_image.dart';
void main() {
testWidgets('Test FadeInImage', (tester) async {
await tester.pumpWidget(FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: 'https://picsum.photos/id/28/200',
));
// First: Solve for "provide your own HttpClient implementation" error
// Second: Test for placeholder image (kTransparentImage)
// expect placeholder image: findsOneWidget
// expect network image: findsNothing
// Third: Wait until network image to appear
// Forth: Test for network image (https://picsum.photos/id/28/200)
// expect placeholder image: findsNothing
// expect network image: findsOneWidget
});
}
this is how i managed to test this:
I am using the network_image_mock to mock network images.
Note: The Dart testing environment doesn't have a concept of real time, so the "wait time" of 700ms doesn't apply here. Instead, pumpAndSettle() is used to simulate the passage of time.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:network_image_mock/network_image_mock.dart';
import 'package:transparent_image/transparent_image.dart';
void main() {
testWidgets('Test FadeInImage', (tester) async {
mockNetworkImagesFor(() async {
await tester.pumpWidget(MaterialApp(
home: FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: 'https://picsum.photos/id/28/200',
),
));
// Test for placeholder image (kTransparentImage)
expect(find.byType(FadeInImage), findsOneWidget);
// Pump a new frame to start the image load
await tester.pump();
// Wait until network image to appear
// Wait for the image to load
await tester.pumpAndSettle();
// Test for network image (https://picsum.photos/id/28/200)
final image = tester.widget<FadeInImage>(find.byType(FadeInImage));
expect(
(image.image as NetworkImage).url, 'https://picsum.photos/id/28/200');
});
});
}
Hope this helps:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With