BnMcG
BnMcG

Reputation: 688

Sinon: Mocking websockets/ws

How can I mock up websockets/ws using Sinon? I'm trying to test that my application behaves as expected when using WebSockets, without necessarily needing to connect each time (eg: testing event handlers, etc).

Coming from a C# background, I'd just mock out the whole interface using a library like Moq, and then verify that my application had made the expected calls.

However, when trying to do this with Sinon, I'm running into errors.

An example of a test:

const WebSocket = require('ws');
const sinon = require('sinon');
const webSocket = sinon.mock(WebSocket);
webSocket.expects('on').withArgs(sinon.match.any, sinon.match.any);
const subject = new MyClass(logger, webSocket);

This class is then calling:

this._webSocket.on("open", () => {
    this.onWebSocketOpen();
});

But when I try and run my tests, I get this error:

TypeError: Attempted to wrap undefined property on as function

What's the correct way to mock out an object like this using Sinon?

Thanks.

Upvotes: 0

Views: 1750

Answers (1)

Vincent
Vincent

Reputation: 1651

If your just trying to test if the given sockets 'on' method was called when passed in, this is how you would do it:

my-class/index.js

class MyClass {
  constructor(socket) {
    this._socket = socket;

    this._socket.on('open', () => {
      //whatever...
    });
  };
};

module.exports = MyClass;

my-class/test/test.js

const chai = require('chai');
const expect = chai.expect;
const sinon = require('sinon');
const sinon_chai = require('sinon-chai');
const MyClass = require('../index.js');
const sb = sinon.sandbox.create();
chai.use(sinon_chai);

describe('MyClass', () => {
  describe('.constructor(socket)', () => {
    it('should call the .prototype.on method of the given socket\n \t' +
        'passing \'open\' as first param and some function as second param', () => {
      var socket = { on: (a,b) => {} };
      var stub = sb.stub(socket, 'on').returns('whatever');
      var inst = new MyClass(socket);
      expect(stub.firstCall.args[0]).to.equal('open');
      expect(typeof stub.firstCall.args[1] === 'function').to.equal(true);
    });
  });
});

Upvotes: 1

Related Questions