Skip to content

Commit 189bafb

Browse files
Merge pull request #10 from TheCodeDaniel/feat/tests
Feat/tests
2 parents 85d85b9 + b6e199c commit 189bafb

File tree

7 files changed

+168
-204
lines changed

7 files changed

+168
-204
lines changed

lib/features/event_sockets/bloc/event_sockets_bloc.dart

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,11 @@ import 'package:socket_probe/features/event_sockets/bloc/event_sockets_state.dar
88
import 'package:socket_probe/features/event_sockets/data/repository/event_sockets_repo_impl.dart';
99

1010
class EventSocketsBloc extends Bloc<EventSocketsEvent, EventSocketsState> {
11-
late EventSocketsRepoImpl _repository;
11+
EventSocketsRepoImpl _repository = EventSocketsRepoImpl("wss://echo.websocket.events", {
12+
"auth": {"token": "userToken"},
13+
"transports": ["websocket"],
14+
"autoConnect": true,
15+
});
1216

1317
StreamSubscription? _messageSubscription;
1418
final List<dynamic> _messages = [];
@@ -36,9 +40,9 @@ class EventSocketsBloc extends Bloc<EventSocketsEvent, EventSocketsState> {
3640
}
3741

3842
_handleConnect(ConnectRequested event, Emitter<EventSocketsState> emit) {
39-
_repository = EventSocketsRepoImpl(event.socketUrl, event.sockedConfigurations);
4043
try {
4144
emit(EventSocketsConnecting());
45+
_repository = EventSocketsRepoImpl(event.socketUrl, event.sockedConfigurations);
4246

4347
_repository.connectToSocket();
4448

@@ -84,9 +88,13 @@ class EventSocketsBloc extends Bloc<EventSocketsEvent, EventSocketsState> {
8488
}
8589

8690
Future<void> _onMessageReceived(MessageReceived event, Emitter<EventSocketsState> emit) async {
87-
// Log the incoming message.
88-
_messages.add("Received: ${event.message}");
89-
emit(EventSocketsConnected(messages: List.from(_messages)));
91+
try {
92+
// Log the incoming message.
93+
_messages.add("Received: ${event.message}");
94+
emit(EventSocketsConnected(messages: List.from(_messages)));
95+
} catch (e) {
96+
emit(EventSocketsError(error: e.toString()));
97+
}
9098
}
9199

92100
Future<void> _onConnectionErrorOccurred(ConnectionErrorOccurred event, Emitter<EventSocketsState> emit) async {

lib/features/event_sockets/data/repository/event_sockets_repo_impl.dart

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ class EventSocketsRepoImpl {
77
final String socketUrl;
88
final dynamic socketOpts;
99

10-
late sio.Socket socket;
10+
sio.Socket? socket;
1111

1212
// A broadcast controller lets multiple listeners receive the stream of messages.
1313
final StreamController<dynamic> _messageController = StreamController<dynamic>.broadcast();
@@ -21,23 +21,23 @@ class EventSocketsRepoImpl {
2121
// Connect to the Socket.IO server
2222
socket = sio.io(url, socketOpts);
2323

24-
socket.on('connect', (message) {
24+
socket?.on('connect', (message) {
2525
// socket.subEvents();
2626
_messageController.add(message);
2727
log('Connected to server');
2828
});
2929

30-
socket.onAny((event, data) {
30+
socket?.onAny((event, data) {
3131
_messageController.add(data);
3232
log("event name: $event, event data: $data");
3333
});
3434

35-
socket.onError((data) {
35+
socket?.onError((data) {
3636
_messageController.addError(data);
3737
log("connection error: $data");
3838
});
3939

40-
socket.onConnectError((data) {
40+
socket?.onConnectError((data) {
4141
_messageController.addError(data);
4242
log("connection error: $data");
4343
});
@@ -49,16 +49,18 @@ class EventSocketsRepoImpl {
4949
Stream<dynamic> get messages => _messageController.stream;
5050

5151
void sendEventMessage(String event, [dynamic data]) {
52-
if (socket.connected) {
53-
socket.emit(event, data);
52+
if (socket == null) return;
53+
if (socket?.connected ?? false) {
54+
socket?.emit(event, data);
5455
} else {
5556
throw Exception("WebSocket connection is not established. Call connect() first.");
5657
}
5758
}
5859

5960
void disconnect() {
60-
if (socket.connected) {
61-
socket.disconnect();
61+
if (socket == null) return;
62+
if (socket?.connected ?? false) {
63+
socket?.disconnect();
6264
log('disconnected from server');
6365
}
6466
}

lib/features/wsprotocol/bloc/wsprotocol_bloc.dart

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ class WsprotocolBloc extends Bloc<WsprotocolEvent, WsprotocolState> {
1010
TextEditingController wssTextController = TextEditingController();
1111
TextEditingController randomStringController = TextEditingController();
1212

13-
late WsprotocolRepoImpl repository;
13+
WsprotocolRepoImpl repository = WsprotocolRepoImpl('wss://echo.websocket.events');
1414
StreamSubscription? _messageSubscription;
1515
final List<dynamic> _messages = [];
1616

@@ -32,7 +32,7 @@ class WsprotocolBloc extends Bloc<WsprotocolEvent, WsprotocolState> {
3232
Future<void> _onConnectRequested(ConnectRequested event, Emitter<WsprotocolState> emit) async {
3333
emit(WsprotocolConnecting());
3434
try {
35-
repository = WsprotocolRepoImpl(wssTextController.text);
35+
repository = WsprotocolRepoImpl(event.socketUrl);
3636
repository.connect();
3737
// Listen for messages from the repository.
3838
_messageSubscription = repository.messages.listen(
@@ -55,10 +55,14 @@ class WsprotocolBloc extends Bloc<WsprotocolEvent, WsprotocolState> {
5555
}
5656

5757
Future<void> _onDisconnectRequested(DisconnectRequested event, Emitter<WsprotocolState> emit) async {
58-
repository.disconnect();
59-
_messages.clear();
60-
await _messageSubscription?.cancel();
61-
emit(WsprotocolDisconnected());
58+
try {
59+
repository.disconnect();
60+
_messages.clear();
61+
await _messageSubscription?.cancel();
62+
emit(WsprotocolDisconnected());
63+
} catch (e) {
64+
emit(WsprotocolError(e.toString()));
65+
}
6266
}
6367

6468
Future<void> _onSendMessageRequested(SendMessageRequested event, Emitter<WsprotocolState> emit) async {
@@ -83,9 +87,13 @@ class WsprotocolBloc extends Bloc<WsprotocolEvent, WsprotocolState> {
8387
}
8488

8589
Future<void> _onMessageReceived(MessageReceived event, Emitter<WsprotocolState> emit) async {
86-
// Log the incoming message.
87-
_messages.add("Received: ${event.message}");
88-
emit(WsprotocolConnected(messages: List.from(_messages)));
90+
try {
91+
// Log the incoming message.
92+
_messages.add("Received: ${event.message}");
93+
emit(WsprotocolConnected(messages: List.from(_messages)));
94+
} catch (e) {
95+
emit(WsprotocolError(e.toString()));
96+
}
8997
}
9098

9199
Future<void> _onConnectionErrorOccurred(ConnectionErrorOccurred event, Emitter<WsprotocolState> emit) async {

lib/features/wsprotocol/bloc/wsprotocol_event.dart

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,13 @@ abstract class WsprotocolEvent extends Equatable {
99
}
1010

1111
/// Event to initiate a connection.
12-
class ConnectRequested extends WsprotocolEvent {}
12+
class ConnectRequested extends WsprotocolEvent {
13+
final String socketUrl;
14+
const ConnectRequested({required this.socketUrl});
15+
16+
@override
17+
List<Object?> get props => [socketUrl];
18+
}
1319

1420
/// Event to close the connection.
1521
class DisconnectRequested extends WsprotocolEvent {}

lib/features/wsprotocol/presentation/screens/wsprotocol_view.dart

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,9 @@ class _WsprotocolViewState extends State<WsprotocolView> {
7070
protocolBloc.add(DisconnectRequested());
7171
return;
7272
}
73-
protocolBloc.add(ConnectRequested());
73+
protocolBloc.add(ConnectRequested(
74+
socketUrl: protocolBloc.wssTextController.text
75+
));
7476
},
7577
content: isLoading
7678
? SizedBox(height: 20, width: 20, child: CircularProgressIndicator(color: Colors.white))
Lines changed: 60 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -1,103 +1,69 @@
1-
// import 'dart:async';
1+
import 'package:bloc_test/bloc_test.dart';
2+
import 'package:flutter_test/flutter_test.dart';
3+
import 'package:socket_probe/features/event_sockets/bloc/event_sockets_bloc.dart';
4+
import 'package:socket_probe/features/event_sockets/bloc/event_sockets_event.dart';
5+
import 'package:socket_probe/features/event_sockets/bloc/event_sockets_state.dart';
26

3-
// import 'package:flutter_test/flutter_test.dart';
4-
// import 'package:bloc_test/bloc_test.dart';
5-
// import 'package:mocktail/mocktail.dart';
6-
// import 'package:socket_probe/features/event_sockets/bloc/event_sockets_bloc.dart';
7-
// import 'package:socket_probe/features/event_sockets/bloc/event_sockets_event.dart';
8-
// import 'package:socket_probe/features/event_sockets/bloc/event_sockets_state.dart';
9-
// import 'package:socket_probe/features/event_sockets/data/repository/event_sockets_repo_impl.dart';
7+
void main() {
8+
group(EventSocketsBloc, () {
9+
late EventSocketsBloc eventSocketsBloc;
1010

11-
// // Mock repository class
12-
// class MockEventSocketsRepo extends Mock implements EventSocketsRepoImpl {}
11+
setUp(() {
12+
eventSocketsBloc = EventSocketsBloc();
13+
});
1314

14-
// void main() {
15-
// late EventSocketsBloc eventSocketsBloc;
16-
// late MockEventSocketsRepo mockRepository;
17-
// late StreamController<dynamic> messageController;
15+
blocTest(
16+
'This test the websocket connection when ConnectedRequest is added',
17+
build: () => eventSocketsBloc,
18+
act: (bloc) => bloc.add(
19+
ConnectRequested(socketUrl: 'wss://echo.websocket.events', sockedConfigurations: {
20+
"auth": {"token": "userToken"},
21+
"transports": ["websocket"],
22+
"autoConnect": true,
23+
}),
24+
),
25+
expect: () => [
26+
isA<EventSocketsConnecting>(),
27+
isA<EventSocketsConnected>(),
28+
],
29+
);
1830

19-
// setUp(() {
20-
// mockRepository = MockEventSocketsRepo();
21-
// messageController = StreamController<dynamic>.broadcast();
31+
blocTest(
32+
'This test the websocket connection when DisconnectRequested is added',
33+
build: () => eventSocketsBloc,
34+
act: (bloc) => bloc.add(DisconnectRequested()),
35+
expect: () => [isA<EventSocketsDisconnected>()],
36+
);
2237

23-
// when(() => mockRepository.messages).thenAnswer((_) => messageController.stream);
24-
// when(() => mockRepository.connectToSocket()).thenAnswer((_) {
25-
// messageController.add('Connected'); // Simulating successful connection
26-
// });
27-
// when(() => mockRepository.disconnect()).thenReturn(null);
28-
// when(() => mockRepository.sendEventMessage(any(), any())).thenReturn(null);
38+
blocTest(
39+
'This test the websocket connection when SendMessageRequested is added',
40+
build: () => eventSocketsBloc,
41+
act: (bloc) => bloc.add(
42+
SendMessageRequested(message: "Send Message Requested", event: "message.event"),
43+
),
44+
expect: () => [isA<EventSocketsConnected>()],
45+
);
2946

30-
// eventSocketsBloc = EventSocketsBloc();
31-
// // eventSocketsBloc._repository = mockRepository;
32-
// });
47+
blocTest(
48+
'This test the websocket connection when MessageReceived is added',
49+
build: () => eventSocketsBloc,
50+
act: (bloc) => bloc.add(
51+
MessageReceived(message: "Message Received"),
52+
),
53+
expect: () => [isA<EventSocketsConnected>()],
54+
);
3355

34-
// tearDown(() {
35-
// eventSocketsBloc.close();
36-
// messageController.close();
37-
// });
56+
blocTest(
57+
'This test the websocket connection when ConnectionErrorOccurred is added',
58+
build: () => eventSocketsBloc,
59+
act: (bloc) => bloc.add(
60+
ConnectionErrorOccurred(message: "Connection Error Occurred"),
61+
),
62+
expect: () => [isA<EventSocketsError>()],
63+
);
3864

39-
// test('initial state should be EventSocketsInitial', () {
40-
// expect(eventSocketsBloc.state, equals(EventSocketsInitial()));
41-
// });
65+
tearDown(() => eventSocketsBloc.close());
4266

43-
// blocTest<EventSocketsBloc, EventSocketsState>(
44-
// 'emits [EventSocketsConnecting, EventSocketsConnected] when ConnectRequested is added',
45-
// build: () => eventSocketsBloc,
46-
// act: (bloc) => bloc.add(ConnectRequested(socketUrl: 'ws://test-url', sockedConfigurations: {})),
47-
// expect: () => [
48-
// EventSocketsConnecting(),
49-
// EventSocketsConnected(messages: []),
50-
// ],
51-
// verify: (_) {
52-
// verify(() => mockRepository.connectToSocket()).called(1);
53-
// },
54-
// );
55-
56-
// blocTest<EventSocketsBloc, EventSocketsState>(
57-
// 'emits [EventSocketsDisconnected] when DisconnectRequested is added',
58-
// build: () => eventSocketsBloc,
59-
// act: (bloc) => bloc.add(DisconnectRequested()),
60-
// expect: () => [
61-
// EventSocketsDisconnected(),
62-
// ],
63-
// verify: (_) {
64-
// verify(() => mockRepository.disconnect()).called(1);
65-
// },
66-
// );
67-
68-
// blocTest<EventSocketsBloc, EventSocketsState>(
69-
// 'emits [EventSocketsConnected] when a message is received',
70-
// build: () => eventSocketsBloc,
71-
// act: (bloc) {
72-
// messageController.add('New Event Message');
73-
// bloc.add(MessageReceived(message: 'New Event Message'));
74-
// },
75-
// expect: () => [
76-
// EventSocketsConnected(messages: ['Received: New Event Message']),
77-
// ],
78-
// );
79-
80-
// blocTest<EventSocketsBloc, EventSocketsState>(
81-
// 'emits [EventSocketsConnected] when SendMessageRequested is added',
82-
// build: () => eventSocketsBloc,
83-
// act: (bloc) => bloc.add(SendMessageRequested(event: 'testEvent', message: 'testMessage')),
84-
// expect: () => [
85-
// EventSocketsConnected(messages: ['Sent: testMessage']),
86-
// ],
87-
// verify: (_) {
88-
// verify(() => mockRepository.sendEventMessage('testEvent', 'testMessage')).called(1);
89-
// },
90-
// );
91-
92-
// blocTest<EventSocketsBloc, EventSocketsState>(
93-
// 'emits [EventSocketsError] when a connection error occurs',
94-
// build: () => eventSocketsBloc,
95-
// act: (bloc) {
96-
// messageController.addError('Socket connection failed');
97-
// bloc.add(ConnectionErrorOccurred(message: 'Socket connection failed'));
98-
// },
99-
// expect: () => [
100-
// EventSocketsError(error: 'Socket connection failed'),
101-
// ],
102-
// );
103-
// }
67+
// end of test
68+
});
69+
}

0 commit comments

Comments
 (0)