Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

socket mock

var socketMock;
var windowMock;
var address = 'ws://test.address';

describe(".init(address, window)", function() {
  beforeEach(function() {
    var WebSocket = jasmine.createSpy();
    WebSocket.and.callFake(function (url) {
      socketMock = {
        url: url,
        readyState: WebSocket.CONNECTING,
        send: jasmine.createSpy(),
        close: jasmine.createSpy().and.callFake(function () {
          socketMock.readyState = WebSocket.CLOSING;
        }),

        // methods to mock the internal behaviour of the real WebSocket
        _open: function () {
          socketMock.readyState = WebSocket.OPEN;
          socketMock.onopen && socketMock.onopen();
        },
        _message: function (msg) {
          socketMock.onmessage && socketMock.onmessage({data: msg});
        },
        _error: function () {
          socketMock.readyState = WebSocket.CLOSED;
          socketMock.onerror && socketMock.onerror();
        },
        _close: function () {
          socketMock.readyState = WebSocket.CLOSED;
          socketMock.onclose && socketMock.onclose();
        }
      };
      return socketMock;
    });
    WebSocket.CONNECTING = 0;
    WebSocket.OPEN = 1;
    WebSocket.CLOSING = 2;
    WebSocket.CLOSED = 3;

    windowMock = {
      WebSocket: WebSocket
    };
    spyOn(subject, 'handleMessage');
  });

  it("should create a WebSocket client which connects to the given address", function() {
    subject.init(address, windowMock);
    expect(windowMock.WebSocket).toHaveBeenCalledWith(address);
  });

  it("should have onmessage method overriden with a function which handles message", function() {
    var message = 'hello socket';
    subject.init(address, window);

    // pretend the socket connected (optional)
    socketMock._open();

    // pretend the socket got a message
    socketMock._message(message)

    expect(subject.handleMessage).toHaveBeenCalledWith(message);
  });
});
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #socket #mock
ADD COMMENT
Topic
Name
9+4 =