Skip to content

Instantly share code, notes, and snippets.

@yshean
Last active July 1, 2022 10:43
Show Gist options
  • Save yshean/e8c578260c76603ad4cb57393db8386a to your computer and use it in GitHub Desktop.
Save yshean/e8c578260c76603ad4cb57393db8386a to your computer and use it in GitHub Desktop.
Unit / widget test: test the NetworkImage or Image.network properties
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail_image_network/mocktail_image_network.dart';
testWidgets(
'renders an image with the provided image url',
(tester) async {
const expectedImageUrl = 'media.giphy.com/example.jpg';
await mockNetworkImages(() async {
await tester.pumpWidget(app); // your app is a widget that contains your network image
/** You should also wrap your NetworkImage or Image.network with a DecoratedBox or other widget as the parent,
because finder only finds a "widget", and BoxDecoration/DecorationImage/NetworkImage are NOT a widget.
Example:
app = DecoratedBox(
decoration: BoxDecoration(
borderRadius: const BorderRadius.vertical(
bottom: Radius.circular(8),
),
image: DecorationImage(
image: NetworkImage(imageUrl),
fit: BoxFit.cover,
),
),
);
*/
});
expect(
find.byWidgetPredicate(
(Widget widget) =>
// always start finding from a "widget", then drill down the child until you find your NetworkImage
widget is DecoratedBox &&
(((widget.decoration as BoxDecoration).image)?.image
as NetworkImage?)
?.url ==
expectedImageUrl,
),
findsOneWidget,
);
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment