Skip to content

Commit

Permalink
feat(mocktail_image_network): add customizable imageBytes (#214)
Browse files Browse the repository at this point in the history
  • Loading branch information
ABausG committed Jan 19, 2024
1 parent 5d4573a commit 53e8132
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
@@ -1,5 +1,6 @@
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:mocktail/mocktail.dart';

Expand Down Expand Up @@ -39,10 +40,12 @@ import 'package:mocktail/mocktail.dart';
/// }
/// ```
/// {@endtemplate}
T mockNetworkImages<T>(T Function() body) {
T mockNetworkImages<T>(T Function() body, {Uint8List? imageBytes}) {
return HttpOverrides.runZoned(
body,
createHttpClient: (_) => _createHttpClient(),
createHttpClient: (_) => _createHttpClient(
data: imageBytes ?? _transparentPixelPng,
),
);
}

Expand All @@ -59,7 +62,7 @@ class _MockHttpClientResponse extends Mock implements HttpClientResponse {}

class _MockHttpHeaders extends Mock implements HttpHeaders {}

HttpClient _createHttpClient() {
HttpClient _createHttpClient({required List<int> data}) {
final client = _MockHttpClient();
final request = _MockHttpClientRequest();
final response = _MockHttpClientResponse();
Expand All @@ -79,7 +82,7 @@ HttpClient _createHttpClient() {
final onData =
invocation.positionalArguments[0] as void Function(List<int>);
final onDone = invocation.namedArguments[#onDone] as void Function()?;
return Stream<List<int>>.fromIterable(<List<int>>[_transparentPixelPng])
return Stream<List<int>>.fromIterable(<List<int>>[data])
.listen(onData, onDone: onDone);
});
when(() => request.headers).thenReturn(headers);
Expand Down
Expand Up @@ -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 = <int>[];

response.listen(data.addAll);

// Wait for all microtasks to run
await Future<void>.delayed(Duration.zero);

expect(data, equals(greenPixel));
},
imageBytes: greenPixel,
);
});
});
}

0 comments on commit 53e8132

Please sign in to comment.