bloc_test 3.1.0

Bloc Test Package

Pub build codecov style: effective dart Flutter.io Awesome Flutter Flutter Samples Star on GitHub Discord License: MIT


A Dart package that makes testing blocs easy. Built to work with bloc and mockito.

Create a Mock Bloc #

import 'package:bloc_test/bloc_test.dart';

class MockCounterBloc extends MockBloc<CounterEvent, int> implements CounterBloc {}

Stub the Bloc Stream #

whenListen creates a stub response for the listen method on a Bloc. Use whenListen if you want to return a canned Stream of states for a bloc instance.

// Create a mock instance
final counterBloc = MockCounterBloc();

// Stub the bloc `Stream`
whenListen(counterBloc, Stream.fromIterable([0, 1, 2, 3]));

// Assert that the bloc emits the stubbed `Stream`.
expectLater(counterBloc, emitsInOrder(<int>[0, 1, 2, 3])))

Unit Test a Real Bloc with blocTest #

blocTest creates a new bloc-specific test case with the given description. blocTest will handle asserting that the bloc emits the expected states (in order) after act is executed. blocTest also handles ensuring that no additional states are emitted by closing the bloc stream before evaluating the expectation.

build should be used for all bloc initialization and preparation and must return the bloc under test.

act is an optional callback which will be invoked with the bloc under test and should be used to add events to the bloc.

wait is an optional Duration which can be used to wait for async operations within the bloc under test such as debounceTime.

expect is an Iterable<State> which the bloc under test is expected to emit after act is executed.

verify is an optional callback which is invoked after expect and can be used for additional non-bloc related assertions.

group('CounterBloc', () {
  blocTest(
    'emits [0] when nothing is added',
    build: () => CounterBloc(),
    expect: [0],
  );

  blocTest(
    'emits [0, 1] when CounterEvent.increment is added',
    build: () => CounterBloc(),
    act: (bloc) => bloc.add(CounterEvent.increment),
    expect: [0, 1],
  );
});

blocTest can also be used to verify internal bloc functionality.

blocTest(
  'CounterBloc emits [0, 1] when CounterEvent.increment is added',
  build: () => CounterBloc(),
  act: (bloc) => bloc.add(CounterEvent.increment),
  expect: [0, 1],
  verify: () async {
    verify(repository.someMethod(any)).called(1);
  }
);

blocTest can also be used to wait for async operations like debounceTime by providing a Duration to wait.

blocTest(
  'CounterBloc emits [0, 1] when CounterEvent.increment is added',
  build: () => CounterBloc(),
  act: (bloc) => bloc.add(CounterEvent.increment),
  wait: const Duration(milliseconds: 300),
  expect: [0, 1],
);

Note: when using blocTest with state classes which don't override == and hashCode you can provide an Iterable of matchers instead of explicit state instances.

blocTest(
  'emits [StateA, StateB] when MyEvent is added',
  build: () => MyBloc(),
  act: (bloc) => bloc.add(MyEvent()),
  expect: [isA<StateA>(), isA<StateB>()],
);

Assert with Confidence using emitsExactly #

emitsExactly is similar to emitsInOrder but asserts that the provided bloc emits only the expected states in the exact order in which they were provided.

group('CounterBloc', () {
  test('emits [0] when nothing is added', () async {
    final bloc = CounterBloc();
    await emitsExactly(bloc, [0]);
  });

  test('emits [0, 1] when CounterEvent.increment is added', () async {
    final bloc = CounterBloc();
    bloc.add(CounterEvent.increment);
    await emitsExactly(bloc, [0, 1]);
  });
});

emitsExactly also supports Matchers for states which don't override == and hashCode.

test('emits [StateA, StateB] when EventB is added', () async {
  final bloc = MyBloc();
  bloc.add(EventB());
  await emitsExactly(bloc, [isA<StateA>(), isA<StateB>()]);
});

emitsExactly also takes an optional duration which is useful in cases where the bloc is using debounceTime or other similar operators.

test('emits [0, 1] when CounterEvent.increment is added', () async {
  final bloc = CounterBloc();
  bloc.add(CounterEvent.increment);
  await emitsExactly(bloc, [0, 1], duration: const Duration(milliseconds: 300));
});

Dart Versions #

  • Dart 2: >= 2.6.0

Maintainers #

3.1.0 #

  • Add verify to blocTest (#781)

3.0.1 #

  • Enable blocTest to add more than one asynchronous event at a time (#724)

3.0.0 #

  • Update to bloc: ^3.0.0
  • emitsExactly supports optional duration for async operators like debounceTime (#726)
  • blocTest supports optional wait for async operators like debounceTime (#726)

3.0.0-dev.1 #

  • Update to bloc: ^3.0.0-dev.1

2.2.2 #

  • Minor internal improvements (fixed analysis warning in emitsExactly)

2.2.1 #

  • Minor documentation improvements (syntax highlighting in README)

2.2.0 #

  • emitsExactly and blocTest support Iterable<Matcher (#695)

2.1.0 #

  • Add MockBloc to bloc_test in order to simplify bloc mocks (addresses #636)
  • Documentation and example updates

2.0.0 #

1.0.0 #

Updated to bloc: ^1.0.0 and Documentation Updates

0.2.1 #

whenListen automatically converts Stream to BroadcastStream

0.2.0 #

whenListen handles internal skip from BlocBuilder and BlocListener

0.1.0 #

Initial Version of the library.

  • Includes whenListen to enable mocking a Bloc state Stream.

example/main.dart

import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:bloc_test/bloc_test.dart';
import 'package:test/test.dart';

enum CounterEvent { increment }

class CounterBloc extends Bloc<CounterEvent, int> {
  @override
  int get initialState => 0;

  @override
  Stream<int> mapEventToState(
    CounterEvent event,
  ) async* {
    switch (event) {
      case CounterEvent.increment:
        yield state + 1;
        break;
    }
  }
}

// Mock Bloc
class MockCounterBloc extends MockBloc<CounterEvent, int>
    implements CounterBloc {}

void main() {
  group('whenListen', () {
    test("Let's mock the CounterBloc's stream!", () {
      // Create Mock CounterBloc Instance
      final counterBloc = MockCounterBloc();

      // Stub the listen with a fake Stream
      whenListen(counterBloc, Stream.fromIterable([0, 1, 2, 3]));

      // Expect that the CounterBloc instance emitted the stubbed Stream of
      // states
      expectLater(counterBloc, emitsInOrder(<int>[0, 1, 2, 3]));
    });
  });

  group('emitsExactly', () {
    test('emits [0] when nothing is added', () async {
      final bloc = CounterBloc();
      await emitsExactly(bloc, [0]);
    });

    test('emits [0, 1] when CounterEvent.increment is added', () async {
      final bloc = CounterBloc();
      bloc.add(CounterEvent.increment);
      await emitsExactly(bloc, [0, 1]);
    });
  });

  group('blocTest', () {
    blocTest(
      'emits [0] when nothing is added',
      build: () => CounterBloc(),
      expect: [0],
    );

    blocTest(
      'emits [0, 1] when CounterEvent.increment is added',
      build: () => CounterBloc(),
      act: (bloc) => bloc.add(CounterEvent.increment),
      expect: [0, 1],
    );
  });
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  bloc_test: ^3.1.0

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:bloc_test/bloc_test.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
91
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
96
Learn more about scoring.

We analyzed this package on Feb 21, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.5

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.6.0 <3.0.0
bloc ^3.0.0 3.0.0
meta ^1.1.6 1.1.8
mockito ^4.0.0 4.1.1
rxdart ^0.23.0 0.23.1
test ^1.3.0 1.12.0
Transitive dependencies
_fe_analyzer_shared 1.0.3
analyzer 0.39.4
args 1.5.2
async 2.4.0
boolean_selector 2.0.0
charcode 1.1.3
collection 1.14.12
convert 2.1.1
coverage 0.13.6
crypto 2.1.4
csslib 0.16.1
glob 1.2.0
html 0.14.0+3
http 0.12.0+4
http_multi_server 2.2.0
http_parser 3.1.3
io 0.3.3
js 0.6.1+1
logging 0.11.4
matcher 0.12.6
mime 0.9.6+3
multi_server_socket 1.0.2
node_interop 1.0.3
node_io 1.0.1+2
node_preamble 1.4.8
package_config 1.1.0
package_resolver 1.0.10
path 1.6.4
pedantic 1.9.0
pool 1.4.0
pub_semver 1.4.3
shelf 0.7.5
shelf_packages_handler 1.0.4 2.0.0
shelf_static 0.2.8
shelf_web_socket 0.2.3
source_map_stack_trace 1.1.5
source_maps 0.10.9
source_span 1.6.0
stack_trace 1.9.3
stream_channel 2.0.0
string_scanner 1.0.5
term_glyph 1.1.0
test_api 0.2.14
test_core 0.3.0
typed_data 1.1.6
vm_service 2.3.1
watcher 0.9.7+13
web_socket_channel 1.1.0
webkit_inspection_protocol 0.5.0
yaml 2.2.0
Dev dependencies
effective_dart ^1.2.0
test_coverage ^0.2.0