TestingMedium30 XP4 min read
How do you test BLoC with bloc_test?
TL;DR: The bloc_test package provides blocTest<B, S>() that adds events, then asserts an expected sequence of emitted states. It also has the expect: [] shorthand for verifying exact state order.
Full Answer
Testing BLoC/Cubit is straightforward because their state output is pure and predictable — given an input event, you expect a specific sequence of states.
blocTest Structure
- ▸build: () => creates the bloc/cubit under test
- ▸act: (bloc) => add events or call cubit methods
- ▸expect: () => [list of expected states emitted]
- ▸verify: (bloc) => assert side effects (repository calls etc.)
🎯
Use setUp to build fresh mocks, tearDown to close blocs. Blocs hold resources (streams) that must be closed.
Code Examples
dartTesting a Cubit with bloc_test
Output
// Both tests pass — exact state sequence verified
Common Mistakes
- ✗Forgetting to close bloc in tearDown — leaks stream subscriptions
- ✗Using equatable incorrectly on state classes — two states that should be equal fail comparison
Interview Tip
💡
bloc_test makes BLoC testing readable and declarative. Show you know the full build/act/expect/verify cycle and why tearDown matters.
#bloc_test#cubit#state-sequence#bloc