将假客户端连接到ws WebSocket模块

时间:2018-10-21 00:32:33

标签: node.js websocket

所以我有一个围绕ws模块构建的WebSocket包装器,并且我正在尝试创建一个测试套件,但是我无法使用传统意义上的WebSocket,因为它需要将其连接到网页,所以我想可以“伪造”客户端并将其连接到ws WebSocketServer。

但是,我不知道如何仅将客户端添加到clients集中就如何将客户端添加到服务器,但是这样就不会触发客户端的wss.on('connection')我需要在其中测试的代码路径。

是否可以将伪造的客户端与ws模块一起使用,或者有更好的方法呢?

测试

const http = require('http').Server;
const chai = require('chai');
const WebSocketServer = require('../index');
const MockClient = require('./MockClient');

let app;

describe('The WebSocketServer should acknowledge new client has connected', () => {

  beforeEach((done) => {

    app = new WebSocketServer(http());

    const mock1 = new MockClient();

    done();

  });

  afterEach((done) => {

    app = null;

    done();

  });

  it('Should follow a code path in the connecting event (where the console.log placeholder is now)', (done) => {

    done();

  });

});

WebSocketServer.js

'use strict'

const WebSocket = require('ws').Server;

module.exports = class WebSocketServer {

    constructor(server) {

        this.server = server;

        this.wss = new WebSocket({ server: this.server, clientTracking: true });

        this.wss.on('connection', (ws, req) => {
            console.log('client connected');
        });

    }

}

MockClient.js

'use strict'

const EventEmitter = require('events').EventEmitter;

module.exports = class MockClient extends EventEmitter {

  constructor() {

    super();

    this.STATUS = {
      CONNECTING: 0,
      OPENED: 1,
      CLOSED: 3
    };

    this.readyState = this.STATUS.CONNECTING;

    this.messages = [];

  }

  send(message) {

    this.messages.push(message);

    this.emit('message', message);

  }

  open() {

    this.readyState = this.STATUS.OPENED;

  }

  close(code, reason) {

    this.readyState = this.STATUS.CLOSED;

    this.emit('close', { closeCode: code, reason: reason });

  }

}

0 个答案:

没有答案