BLoC PatternMedium30 XP4 min read
How do you test a Bloc using bloc_test?
TL;DR: Use blocTest() from the bloc_test package. Provide: bloc (factory), seed (initial state), act (events to add), expect (list of expected emitted states). Use whenListen for stream-based blocs.
Full Answer
blocTest() replaces manual Stream testing with a declarative API. It runs the bloc, adds events, and asserts that states are emitted in the correct order.
- ▸build: Factory function that creates the bloc (supports mocking dependencies)
- ▸seed: Optional function that sets up initial state before act runs
- ▸act: Function that adds events or calls methods on the bloc
- ▸expect: List of expected emitted states — matched with Matchers
- ▸verify: Optional callback to verify mock calls after the test
- ▸errors: Expected thrown errors if the bloc handler throws
Code Examples
dartblocTest with mocked repository
Output
// Test passes: states emitted in exact order // verify: ensures repo.getByCategory was called exactly once
Common Mistakes
- ✗Expecting state equality without implementing == — use equatable or Freezed
- ✗Not calling setUp/tearDown for mocks — leads to test pollution between tests
Interview Tip
💡
Show the full test with mock, act, expect, and verify. Mention that bloc_test uses the expect() matcher, so you can use isA<QuizError>() for partial matching.
#bloc-test#unit-test#act#expect#seed