Line data Source code
1 : import 'dart:async';
2 :
3 : import 'package:bloc/bloc.dart';
4 : import 'package:mocktail/mocktail.dart';
5 :
6 : /// Creates a stub response for the `listen` method on a [bloc].
7 : /// Use [whenListen] if you want to return a canned `Stream` of states
8 : /// for a [bloc] instance.
9 : ///
10 : /// [whenListen] also handles stubbing the `state` of the [bloc] to stay
11 : /// in sync with the emitted state.
12 : ///
13 : /// Return a canned state stream of `[0, 1, 2, 3]`
14 : /// when `counterBloc.stream.listen` is called.
15 : ///
16 : /// ```dart
17 : /// whenListen(counterBloc, Stream.fromIterable([0, 1, 2, 3]));
18 : /// ```
19 : ///
20 : /// Assert that the `counterBloc` state `Stream` is the canned `Stream`.
21 : ///
22 : /// ```dart
23 : /// await expectLater(
24 : /// counterBloc.stream,
25 : /// emitsInOrder(
26 : /// <Matcher>[equals(0), equals(1), equals(2), equals(3), emitsDone],
27 : /// )
28 : /// );
29 : /// expect(counterBloc.state, equals(3));
30 : /// ```
31 : ///
32 : /// Optionally provide an [initialState] to stub the state of the [bloc]
33 : /// before any subscriptions.
34 : ///
35 : /// ```dart
36 : /// whenListen(
37 : /// counterBloc,
38 : /// Stream.fromIterable([0, 1, 2, 3]),
39 : /// initialState: 0,
40 : /// );
41 : ///
42 : /// expect(counterBloc.state, equals(0));
43 : /// ```
44 1 : void whenListen<State>(
45 : BlocBase<State> bloc,
46 : Stream<State> stream, {
47 : State? initialState,
48 : }) {
49 1 : final broadcastStream = stream.asBroadcastStream();
50 :
51 : if (initialState != null) {
52 5 : when(() => bloc.state).thenReturn(initialState);
53 : }
54 :
55 2 : when(
56 : // ignore: deprecated_member_use
57 2 : () => bloc.listen(
58 1 : any(),
59 1 : onDone: any(named: 'onDone'),
60 1 : onError: any(named: 'onError'),
61 1 : cancelOnError: any(named: 'cancelOnError'),
62 : ),
63 2 : ).thenAnswer((invocation) {
64 1 : return broadcastStream.listen(
65 1 : (state) {
66 5 : when(() => bloc.state).thenReturn(state);
67 3 : (invocation.positionalArguments.first as Function(State)).call(state);
68 : },
69 2 : onError: invocation.namedArguments[#onError] as Function?,
70 2 : onDone: invocation.namedArguments[#onDone] as void Function()?,
71 2 : cancelOnError: invocation.namedArguments[#cancelOnError] as bool?,
72 : );
73 : });
74 :
75 5 : when(() => bloc.stream).thenAnswer(
76 3 : (_) => broadcastStream.map((state) {
77 5 : when(() => bloc.state).thenReturn(state);
78 : return state;
79 : }),
80 : );
81 : }
|