DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Testing socket.io Apps

Swizec Teller user avatar by
Swizec Teller
·
Feb. 01, 13 · Interview
Like (0)
Save
Tweet
Share
13.53K Views

Join the DZone community and get the full member experience.

Join For Free

nyan cat testing

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 .

first, something to test

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);
// the important parts of echo server
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

automating the test

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) {
        // start the server
        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:

  1. connect client to server
  2. once there’s a connection, listen for echo event from the server
  3. emit echo event to the server
  4. server responds and triggers our listener
  5. listener checks correctness of response
  6. 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.

nyan cat testing

ps: you can see all the code on github .

Socket.IO app

Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Why It Is Important To Have an Ownership as a DevOps Engineer
  • When AI Strengthens Good Old Chatbots: A Brief History of Conversational AI
  • Efficiently Computing Permissions at Scale: Our Engineering Approach
  • A Guide To Successful DevOps in Web3

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: