How to add unit tests for Node.js and Socket.io?

Sometimes, we want to add unit tests for Node.js and Socket.io.

In this article, we’ll look at how to add unit tests for Node.js and Socket.io.

How to add unit tests for Node.js and Socket.io?

To add unit tests for Node.js and Socket.io, we can set up our socket.io connection before each test, and clear the connection after each test.

For instance, we write

const io = require('socket.io-client')
const assert = require('assert')
const expect = require('expect.js');

describe('Suite of unit tests', () => {
  let socket;

  beforeEach((done) => {
    socket = io.connect('http://localhost:3001', {
      'reconnection delay': 0,
      'reopen delay': 0,
      'force new connection': true
    });
    socket.on('connect', () => {
      console.log('worked...');
      done();
    });
    socket.on('disconnect', () => {
      console.log('disconnected...');
    })
  });

  afterEach((done) => {
    if (socket.connected) {
      console.log('disconnecting...');
      socket.disconnect();
    } else {
      console.log('no connection to break...');
    }
    done();
  });

  describe('First test', () => {

    it('Doing some things with indexOf()', (done) => {
      expect([1, 2, 3].indexOf(5)).to.be.equal(-1);
      expect([1, 2, 3].indexOf(0)).to.be.equal(-1);
      done();
    });

    it('Doing something else with indexOf()', (done) => {
      expect([1, 2, 3].indexOf(5)).to.be.equal(-1);
      expect([1, 2, 3].indexOf(0)).to.be.equal(-1);
      done();
    });

  });

});

to call io.connect in the beforeEach callback to connect to our socket.io server before each test.

The we call done in the 'connect' event callback to run our test.

Likewise, we in the afterEach callback, we call socket.disconnect to disconnect from our socket.io server after each test is socket.connected is true.

Then in our tests, we run some test code and then call done when we’re done.

Conclusion

To add unit tests for Node.js and Socket.io, we can set up our socket.io connection before each test, and clear the connection after each test.