flutter – Testing WebSocket connections

I’m using WebSocket from dart:io and IOWebSocketChannel (https://pub.dev/packages/web_socket_channel) to create a connection with channel subscriptions.
The code is largely working, I can connect to my server and subscribe to channels, receive data etc, but I’m struggling with an approach to writing tests.

Given this constructor:

  SocketServer.Connect(this.url, {this.onConnect}) {
    channel = IOWebSocketChannel.connect(url);
    _stream = channel.stream.listen((data) {

      final payload = jsonDecode(data);
      print('Received: ');
    }, onError: (_)  {

I’ve tried variations on the following:

test("it should create a connection", () async {
      final server = await HttpServer.bind('localhost', 0);
      server.transform(WebSocketTransformer()).listen((WebSocket socket) async {
          final channel = await IOWebSocketChannel(socket);

    bool connected = false;
    final websocketServer = SocketServer.Connect('ws://localhost:${server.port}/cable', onConnect: (SocketServer connection) {
        connected = true;

    expectLater(connected, true);

But I don’t receive the ‘connected’ output, since my HttpServer isn’t sending back the correct responses.

Would it be best to depend on a real server to handle the connections, or create one in the tests?

Product of the Month September 2016

Source link

Leave a Comment

Your email address will not be published. Required fields are marked *