bloc_test 2.1.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 80
Bloc Test Package

Pub Build Status codecov style: effective dart Flutter.io Awesome Flutter Flutter Samples Star on GitHub Gitter 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.

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

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],
    );
});

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]);
    });
});

Dart Versions #

  • Dart 2: >= 2.0.0

Maintainers #

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: ^2.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]
61
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]
80
Learn more about scoring.

We analyzed this package on Nov 15, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.6.0
  • pana: 0.12.21

Platforms

Detected platforms: Flutter, web, other

No platform restriction found in primary library package:bloc_test/bloc_test.dart.

Health suggestions

Fix lib/src/emits_exactly.dart. (-0.50 points)

Analysis of lib/src/emits_exactly.dart reported 1 hint:

line 26 col 3: Future results in async function bodies must be awaited or marked unawaited using package:pedantic.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0 <3.0.0
bloc ^2.0.0 2.0.0
meta ^1.1.6 1.1.8
mockito ^4.0.0 4.1.1
test ^1.3.0 1.9.4
Transitive dependencies
_fe_analyzer_shared 1.0.0
analyzer 0.39.1
args 1.5.2
async 2.4.0
boolean_selector 1.0.5
charcode 1.1.2
collection 1.14.12
convert 2.1.1
coverage 0.13.3+1
crypto 2.1.3
csslib 0.16.1
front_end 0.1.29
glob 1.2.0
html 0.14.0+3
http 0.12.0+2
http_multi_server 2.1.0
http_parser 3.1.3
io 0.3.3
js 0.6.1+1
kernel 0.3.29
logging 0.11.3+2
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.8.0+1
pool 1.4.0
pub_semver 1.4.2
rxdart 0.22.6
shelf 0.7.5
shelf_packages_handler 1.0.4
shelf_static 0.2.8
shelf_web_socket 0.2.3
source_map_stack_trace 1.1.5
source_maps 0.10.8
source_span 1.5.5
stack_trace 1.9.3
stream_channel 2.0.0
string_scanner 1.0.5
term_glyph 1.1.0
test_api 0.2.11
test_core 0.2.15
typed_data 1.1.6
vm_service 2.1.1
watcher 0.9.7+12
web_socket_channel 1.1.0
yaml 2.2.0
Dev dependencies
effective_dart ^1.1.1
test_coverage ^0.2.0