mercredi 31 mars 2021

How to test BLoC listening stream?

I want to test my chat_bloc file which listens several streams:

class ChatBloc extends Bloc<ChatEvent, ChatState> {
  final ChatRepository chatRepository;

  ChatBloc(
      {@required this.chatRepository,})
      : super(ChatLoading()) {

    this.add(ChatScreenStarted());

    _chatSubscription = chatRepository.message.listen((message) { // error points here
      // do smth
    });
  }

  StreamSubscription<Message> _chatSubscription;
  //  mapEventToState and others

  }

Message getter in ChatRepository:

@override
  Stream<Message> get message async* {
    yield* chatDataSource.messages;
  }

Mocking ChatRepository with mockito. And try to test like this:

class MockChatRepository extends Mock implements ChatRepository {}

void main() {
  MockChatsRepository mockChatsRepository;

  ChatBloc chatBloc;

  setUp(() {
    mockChatRepository = MockChatRepository();
    
    chatBloc = ChatBloc(
      chatRepository: mockChatRepository,
    );
  });

  blocTest(
    'sould ...',
    build: () => chatBloc,
    act: (ChatBloc chatBloc) {
      when(mockChatRepository.message)
          .thenReturn(Stream<Message>.fromIterable([tMessageModel]));
      chatBloc.add(ChatScreenStarted());
    },
    expect: () => [],
  );
}

Gives error NoSuchMethodError: The method 'listen' was called on null.

How can I stub that stream?

Aucun commentaire:

Enregistrer un commentaire