title: How to test node.js websocket server?
body: <p>I'm using sockjs with standard configuration.</p>
  
  <pre><code>   var ws = sockjs.createServer();
      ws.on('connection', function(conn) {
          conn.on('data', function(message) {
              wsParser.parse(conn, message)
          });
          conn.on('close', function() {
  
          });
      });
  
      var server = http.createServer(app);
      ws.installHandlers(server, {prefix:'/ws'});
      server.listen(config.server.port, config.server.host);
  </code></pre>
  
  <p><code>wsParser.parse</code> function works like this:</p>
  
  <pre><code>function(conn, message) {
  
  (...)
  
  switch(message.action) {
      case "titleAutocomplete":
          titleAutocomplete(conn, message.data);
          break;
      (...) // a lot more of these
   }
  </code></pre>
  
  <p>Each method called in switch sends back a message to client.</p>
  
  <pre><code>var titleAutocomplete = function(conn, data) {
  
      redis.hgetall("titles:"+data.query, function(err, titles){
          if(err) ERR(err);
  
          if(titles) {
              var response = JSON.stringify({"action": "titleAutocomplete", "data": {"titles": titles}});
              conn.write(response);
          } 
      })
  };
  </code></pre>
  
  <p>Now my problem is that I'd like to make tests for my code (better late than never I guess) and I have no idea how to do it. I started writing normal http tests in with mocha + supertest but I just don't know how to handle websockets. </p>
  
  <p>I'd like to have only one websocket connection to reuse through all tests, I'm binding the websocket connection with user session after first message and I want to test that persistence as well. </p>
  
  <p>How do I make use of ws client's onmessage event and utilize it in my tests? How the tests can tell apart received messages and know which one they are supposed to wait for?</p>