diff --git a/packages/mocktail_image_network/lib/src/mocktail_image_network.dart b/packages/mocktail_image_network/lib/src/mocktail_image_network.dart index 50461d5..2a6b0f3 100644 --- a/packages/mocktail_image_network/lib/src/mocktail_image_network.dart +++ b/packages/mocktail_image_network/lib/src/mocktail_image_network.dart @@ -1,5 +1,6 @@ import 'dart:convert'; import 'dart:io'; +import 'dart:typed_data'; import 'package:mocktail/mocktail.dart'; @@ -39,10 +40,12 @@ import 'package:mocktail/mocktail.dart'; /// } /// ``` /// {@endtemplate} -T mockNetworkImages(T Function() body) { +T mockNetworkImages(T Function() body, {Uint8List? imageBytes}) { return HttpOverrides.runZoned( body, - createHttpClient: (_) => _createHttpClient(), + createHttpClient: (_) => _createHttpClient( + data: imageBytes ?? _transparentPixelPng, + ), ); } @@ -59,7 +62,7 @@ class _MockHttpClientResponse extends Mock implements HttpClientResponse {} class _MockHttpHeaders extends Mock implements HttpHeaders {} -HttpClient _createHttpClient() { +HttpClient _createHttpClient({required List data}) { final client = _MockHttpClient(); final request = _MockHttpClientRequest(); final response = _MockHttpClientResponse(); @@ -79,7 +82,7 @@ HttpClient _createHttpClient() { final onData = invocation.positionalArguments[0] as void Function(List); final onDone = invocation.namedArguments[#onDone] as void Function()?; - return Stream>.fromIterable(>[_transparentPixelPng]) + return Stream>.fromIterable(>[data]) .listen(onData, onDone: onDone); }); when(() => request.headers).thenReturn(headers); diff --git a/packages/mocktail_image_network/test/mocktail_image_network_test.dart b/packages/mocktail_image_network/test/mocktail_image_network_test.dart index cf6bd98..67cb956 100644 --- a/packages/mocktail_image_network/test/mocktail_image_network_test.dart +++ b/packages/mocktail_image_network/test/mocktail_image_network_test.dart @@ -44,5 +44,27 @@ void main() { expect(onDoneCalled, isTrue); }); }); + + test('should properly use custom imageBytes', () async { + final greenPixel = base64Decode( + '''iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M/wHwAEBgIApD5fRAAAAABJRU5ErkJggg==''', + ); + await mockNetworkImages( + () async { + final client = HttpClient()..autoUncompress = false; + final request = await client.getUrl(Uri.https('')); + final response = await request.close(); + final data = []; + + response.listen(data.addAll); + + // Wait for all microtasks to run + await Future.delayed(Duration.zero); + + expect(data, equals(greenPixel)); + }, + imageBytes: greenPixel, + ); + }); }); }