fakes function
Create a pair of fake WebSockets that are connected to each other.
Sending a message on one WebSocket will result in that same message being received by the other.
This can be useful in constructing tests.
For example:
import 'dart:async';
import 'package:test/test.dart';
import 'package:web_socket/src/web_socket.dart';
import 'package:web_socket/testing.dart';
import 'package:web_socket/web_socket.dart';
Future<void> fakeTimeServer(WebSocket webSocket, String time) async {
await webSocket.events.forEach((event) {
switch (event) {
case TextDataReceived():
case BinaryDataReceived():
webSocket.sendText(time);
case CloseReceived():
}
});
}
Future<DateTime> getTime(WebSocket webSocket) async {
webSocket.sendText('');
final time = switch (await webSocket.events.first) {
TextDataReceived(:final text) => DateTime.parse(text),
_ => throw Exception('unexpected response')
};
await webSocket.close();
return time;
}
void main() async {
late WebSocket client;
late WebSocket server;
setUp(() {
(client, server) = fakes();
});
test('test valid time', () async {
unawaited(fakeTimeServer(server, '2024-05-15T01:18:10.456Z'));
expect(
await getTime(client),
DateTime.parse('2024-05-15T01:18:10.456Z'));
});
}
Implementation
(WebSocket, WebSocket) fakes({String protocol = ''}) {
final peer1 = FakeWebSocket(protocol);
final peer2 = FakeWebSocket(protocol);
peer1._other = peer2;
peer2._other = peer1;
return (peer1, peer2);
}