How to use mock-socket - 10 common examples

To help you get started, we’ve selected a few mock-socket examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github t2t2 / vue-syncers-feathers / test / helpers / mock-socket.js View on Github external
emit(event, ...data) {
		if (this.readyState !== BaseSocketIO.OPEN) {
			throw new Error('SocketIO is already in CLOSING or CLOSED state')
		}

		// Emulate connection by re-creating all objects
		data = cloneDeepWith(data, cloneCustomiser)

		const messageEvent = createMessageEvent({
			type: event,
			origin: this.url,
			data
		})

		// Dispatch on self since the event listeners are added to per connection
		this.dispatchEvent(messageEvent, ...data)
	}
github Palindrom / Palindrom / test / specs / client / reconnect.js View on Github external
status: 200,
                    headers: { contentType: 'application/json' },
                    body: `{"witaj": "swiecie", "${remoteVersion}": 777}`
                }, {name: 'reconnect'});
                // wait for HTTP responses and WebSocket server to be established
                await sleep();
                // issue a change that will not get acknoledged by server
                palindrom.obj.hello = 'OT';
                // close the WS
                mockSocketServer.close({
                    code,
                    wasClean,
                    reason
                });
                // setup another web socket so reconnection would not throw an error
                anotherSocket = new MockSocketServer(getTestURL('testURL', false, true));
            });
            if(!wasClean && !reason){
github t2t2 / vue-syncers-feathers / test / helpers / mock-socket.js View on Github external
import {createMessageEvent} from 'mock-socket/src/event-factory'
import cloneDeepWith from 'lodash/cloneDeepWith'

export class Server extends BaseServer {
	// SocketIO sends server (this) as first arg to connection & connect events, this fixes it
	dispatchEvent(event, ...customArguments) {
		if (customArguments[0] && customArguments[0] === this) {
			customArguments.shift()
		}
		return super.dispatchEvent(event, ...customArguments)
	}
}

// SocketIO class isn't exposed
const serverInstance = new Server('dummy')
const instance = new BaseSocketIOConstructor('dummy')
const BaseSocketIO = Object.getPrototypeOf(instance).constructor
instance.on('connect', () => {
	instance.close()
	serverInstance.close()
})
// GG

function cloneCustomiser(arg) {
	if (typeof arg === 'function') {
		return function (...args) {
			args = cloneDeepWith(args, cloneCustomiser)
			return arg(...args)
		}
	}
	return undefined
}
github SuperMap / iClient-JavaScript / test / mapboxgl / services / DataFlowServiceSpec.js View on Github external
describe('mapboxgl_DataFlowService', () => {
    var originalTimeout;
    var service;
    var mockServer = new Server(urlDataFlow);
    beforeAll(() => {
        var e = {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [0, 0]
            },
            "properties": {
                "id": 1
            }
        };
        mockServer.on('connection', socket => {
            socket.on('message', () => {
                console.log("onmessage");
            });
            socket.on('close', () => { });
github ArkEcosystem / desktop-wallet / __tests__ / unit / services / plugin-manager / websocket.spec.js View on Github external
beforeEach(() => {
  if (mockServer) {
    mockServer.stop()
  }

  pongMock = jest.fn(data => {
    if (data === 'ping') {
      mockServer.emit('pong', true)
    }
  })

  mockServer = new Server(host)
  mockServer.on('connection', socket => {
    mockServer.emit('data', 'test')
    socket.on('message', pongMock)
  })
  mockServer.on('message', socket => {
    mockServer.emit('data', 'test')
  })

  const routeCallbacks = []
  routerNext = jest.fn()
  router = {
    beforeEach: jest.fn(callback => {
      routeCallbacks.push(callback)
    }),

    push () {
github logdna / logdna-agent / test / lib / windows-utilities.js View on Github external
it('streams event logs to a socket', function() {
            this.timeout(100000);
            const MockWebSocket = require('mock-socket').WebSocket;
            const MockServer = require('mock-socket').Server;
            var server = new MockServer('ws://localhost:40002');
            var socket = new MockWebSocket('ws://localhost:40002');
            socket.connected = true;
            var lineBuffer = require('../../lib/linebuffer');
            lineBuffer.setSocket(socket);
            var windowsUtilities = requireUncached('../../lib/windows-utilities');

            return new Promise((resolve) => {
                server.on('message', data => {
                    debug('received message!');
                    debug(data);
                    var message = JSON.parse(data);
                    var line = message.ls[0].l;
                    assert.equal(JSON.parse(line).Message, 'arbitraryData');
                    resolve(true);
                });
github logdna / logdna-agent / test / lib / windows-utilities.js View on Github external
it('streams event logs to a socket', function() {
            this.timeout(100000);
            const MockWebSocket = require('mock-socket').WebSocket;
            const MockServer = require('mock-socket').Server;
            var server = new MockServer('ws://localhost:40002');
            var socket = new MockWebSocket('ws://localhost:40002');
            socket.connected = true;
            var lineBuffer = require('../../lib/linebuffer');
            lineBuffer.setSocket(socket);
            var windowsUtilities = requireUncached('../../lib/windows-utilities');

            return new Promise((resolve) => {
                server.on('message', data => {
                    debug('received message!');
                    debug(data);
                    var message = JSON.parse(data);
                    var line = message.ls[0].l;
                    assert.equal(JSON.parse(line).Message, 'arbitraryData');
                    resolve(true);
                });

                setInterval(() => {
github Palindrom / Palindrom / test / specs / client / reconnect.js View on Github external
beforeEach(async () => {
                mockSocketServer = new MockSocketServer(getTestURL('testURL', false, true));
                fetchMock.get(getTestURL('testURL'), {
                    status: 200,
                    headers: { contentType: 'application/json' },
                    body: '{"hello": "world"}'
                }, {name: 'establish'});
                
                onReconnectionCountdown = sinon.spy();
                onReconnectionEnd = sinon.spy();
                palindrom = new Palindrom({
                    remoteUrl: getTestURL('testURL'),
                    ot: true,
                    localVersionPath,
                    remoteVersionPath,
                    onReconnectionCountdown,
                    onReconnectionEnd,
                    useWebSocket: true,
github peers / peerjs / test / peer.ts View on Github external
before(function () {
            const fakeURL = 'ws://localhost:8080/peerjs?key=peerjs&id=1&token=testToken';
            mockServer = new Server(fakeURL);

            mockServer.on('connection', socket => {
                //@ts-ignore
                socket.on('message', data => {
                    socket.send('test message from mock server');
                });

                socket.send(ServerMessageType.Open);
            });
        });
github onsip / SIP.js / test / spec / platform / web / transport.spec.ts View on Github external
function initServer(): void {
    if (mockServer) {
      mockServer.close();
      mockServerWebSocket = undefined;
    }
    mockServer = new Server(
      server,
      { selectProtocol: (protocols: Array) => "sip" }
    );
    mockServer.on("connection", (socket) => {
      logger.log("Mock WebSocket Server: incoming connection");
      mockServerWebSocket = socket;

      socket.on("message", (receivedMessage) => {
        if (typeof receivedMessage !== "string") {
          throw new Error("Mock WebSocket  Server received message not of type string.");
        }
        logger.log(`Mock WebSocket Server: received message "${receivedMessage}"`);
        mockServerReceivedMessage = receivedMessage;
      });

      socket.on("close", () => {

mock-socket

Javascript mocking library for websockets and socket.io

MIT
Latest version published 1 year ago

Package Health Score

63 / 100
Full package analysis