Socket.io is probably one of the coolest things to come out of the JavaScript world in recent years. Finally! Something that lets web developers create real-time apps without the fuss of thinking about websockets and long polling and all the other hacks that need to be used.

The idea is pretty simple, the server can emit an event and the client will pick it up. The converse also happens. Callbacks through the server-client barrier works as well. Socket.io takes care of deciding which of the real-time hacks should be used to make the magic happen.

Thing is, the interplay of client and server makes socket.io apps a bit difficult to test.

A good way I've found is the combination of Mocha, Chai and socket.io-client.

Let's take for example a very simple echo server. I used Express to make things easier to play with in the Chrome console. Here's the relevant part of app.js.

var server = ( exports . server = http . createServer ( app ) . listen ( app . get ( "port" ) , function ( ) { console . log ( "Express server listening on port " + app . get ( "port" ) ) ; } ) ) ; var io = require ( "socket.io" ) . listen ( server ) ; io . set ( "log level" , 0 ) ;

io . sockets . on ( "connection" , function ( socket ) { socket . on ( "echo" , function ( msg , callback ) { callback = callback || function ( ) { } ; socket . emit ( "echo" , msg ) ; callback ( null , "Done." ) ; } ) ; } ) ;

After not forgetting to load /socket.io/socket.io.js into the index page, I can now run the server, point my browser to http://localhost:3000 and play around in the console like this:

> var socket = io.connect("http://localhost:3000") undefined > socket.on("echo", function (msg) { console.log(msg); }) SocketNamespace > socket.emit("echo", "Hello World") SocketNamespace Hello World

Typing commands into a console, even clicking around a webpage is a rather arduous and boring process. The easiest way I've found to automate this is using Mocha and socket.io-client.

First thing we're going to need is requiring everything and making sure the socket.io server is running.

var chai = require ( 'chai' ) , mocha = require ( 'mocha' ) , should = chai . should ( ) ; var io = require ( 'socket.io-client' ) ; describe ( "echo" , function ( ) { var server , options = { transports : [ 'websocket' ] , 'force new connection' : true } ; beforeEach ( function ( done ) { server = require ( '../app' ) . server ; done ( ) ; } ) ;

See, simple :)

Now comes the interesting part, the actual test making sure our server does in fact echo what we ask it to.

it ( "echos message" , function ( done ) { var client = io . connect ( "http://localhost:3000" , options ) ; client . once ( "connect" , function ( ) { client . once ( "echo" , function ( message ) { message . should . equal ( "Hello World" ) ; client . disconnect ( ) ; done ( ) ; } ) ; client . emit ( "echo" , "Hello World" ) ; } ) ; } ) ;

The idea behind this test is simple:

Connect client to server Once there's a connection, listen for echo event from the server Emit _ echo _ event to the server Server responds and triggers our listener Listener checks correctness of response Disconnects client

Disconnecting clients after tests is very important. As I've discovered, not disconnecting can lead to the socket accumulating event listeners, which in turn can fire completely different tests than what you expect. It also leads to tests that pass 70% of the time, but fail in random ways.

In the end, our efforts are rewarded by a happy nyan cat.

PS: you can see all the code on github.

Maria Ramos from Webhostinghub.com/support/edu has translated this post into Spanish.

Did you enjoy this article? 👎 👍

Published on November 30th, 2012 in Client, JavaScript, Programming, Server, Uncategorized, WebSocket

Learned something new?

Want to become a high value JavaScript expert? Here's how it works 👇 Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet 📖right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths. Start with an interactive cheatsheet 📖 Then get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career. "Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌" ~ Ashish Kumar Your Name Your Email Your Address Subscribe & Become an expert 💌 Join over 10,000 engineers just like you already improving their JS careers with my letters, workshops, courses, and talks. ✌️

Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

Ready to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️