IntermediateTesting
How do you unit test a Bloc or Cubit?
Short Answer
Use the bloc_test package's blocTest() helper, which lets you set up a Bloc, feed it events (or call Cubit methods), and assert on the exact sequence of emitted states — without needing any widget tree at all.
Because Blocs and Cubits are pure Dart classes with no Flutter dependency, they're naturally easy to unit test — no pumpWidget or WidgetTester needed. bloc_test's blocTest() reduces the boilerplate of the arrange-act-assert pattern: a build function creating the Bloc, an act function dispatching events, and an expect function returning the list of states you expect to be emitted, in order.
Code Example
blocTest<CounterBloc, int>(
'emits [1] when Increment is added',
build: () => CounterBloc(),
act: (bloc) => bloc.add(Increment()),
expect: () => [1],
);Common Mistakes
- ×Testing Blocs by manually subscribing to the stream and asserting outside blocTest, reinventing what the helper already does more concisely.
- ×Forgetting that blocTest's expect checks the states emitted during act, not the full history including the initial state.