stubbing a socket client with sinon

2k Views Asked by At

i'm trying to stub a socketcluster-client to emit events to the socketserver.

i keep getting the below error from sinon

 TypeError: socket.emit is not a function

this is my test-suite

import {expect} from 'chai';
import sinon from 'sinon'
import io from 'socketcluster-client';
import testServer from '../../server/server.js';

describe('httpServer',() => {


  beforeEach(() => {
    testServer(4000)
  })

  it('should respond to the ping event',() => {
    var socket =sinon.stub(io,'connect')

    var message = 'house'
    socket.emit('ping',message);
  })

})

the connect function usually needs to be called with an argument specifying the port io.connect({port:4000})

how do i stub this with sinon?

i would ideally like to emit events from the stub to check my server response

1

There are 1 best solutions below

6
On

You want to use sinon.spy(), not sinon.stub(). The former will call the original function, the latter won't.

Quote from the documentation:

When wrapping an existing function with a stub, the original function is not called.

You also need to make sure that you actually call it, too, which your current code doesn't seem to be doing.

EDIT: from your comments, it seems to me that all you want to do is run a client, send some messages to the server, and check if the server responds properly. You don't need spies/stubs for that.

I don't know socketcluster, but to give an idea on how it can be implemented, here's an example using a simple HTTP server:

describe('httpServer', () => {

  before((done) => {
    http.createServer((req, res) => {
      res.end(req.url === '/ping' ? 'PONG' : 'HELLO WORLD');
    }).listen(4000, done);
  });

  it('should respond to the ping event', (done) => {

    http.get('http://localhost:4000/ping', (res) => {
      let buffers = [];

      res.on('data', (d) => buffers.push(d))
         .on('end', () => {
           let body = Buffer.concat(buffers);
           expect(body.toString()).to.equal('PONG');
           done();
         });
    });

  });
});

(it's a minimal example, as it doesn't check for errors or clean up the HTTP server after the tests have completed)