简体   繁体   English

使用 jest 的 websocket 服务器“ws”库的单元测试用例

[英]Unit Test cases for websocket server "ws" library using jest

I am trying to figure out how to write unit test cases for Websocket server which is using the ws library.我想弄清楚如何为使用ws库的 Websocket 服务器编写单元测试用例。 I did go through jest-websocket-mock but I think this is for browser based APIs and I want to test server using JEST .我通过jest-websocket-mock做了 go 但我认为这是针对基于浏览器的 API,我想使用JEST测试服务器。

Basic Code: Server.js基本代码:Server.js

import { createServer } from 'https';
import { WebSocketServer } from 'ws';
import { readFileSync } from 'fs';

const server = createServer({
  cert: readFileSync(config.certs.sslCertPath),
  key: readFileSync(config.certs.sslKeyPath),
});

const wss = new WebSocketServer({ noServer: true });

server.on('upgrade', (request, socket, head) => {
  const origin = request && request.headers && request.headers.origin;
  const corsRegex = <regex>;

  if (origin.match(corsRegex) != null) {
    wss.handleUpgrade(request, socket, head, (ws) => {
      wss.emit('connection', ws, request);
    });
  } else {
    socket.destroy();
  }
});

wss.on('connection', (ws, req) => {
  ws.on('message', (messageg) => {
    try {
      console.log(message);
    } catch (error) {
      console.log(error);
    }
  });

  ws.on('close', () => {
    console.log('close');
  });

  ws.on('error', (error) => {
    console.log(error);
  }); 
});

Can someone please help me with how can I test the original server?有人可以帮助我如何测试原始服务器吗?

you need to create some kind of dependency injection mechanism here lets for example move all the socket initialization logic into a separate function您需要在此处创建某种依赖注入机制,例如将所有套接字初始化逻辑移至单独的 function

function initSocketEvents(wss) {
    wss.on('connection', (ws, req) => {
        ws.on('message', (messageg) => {
            try {
                console.log(message);
            } catch (error) {
                console.log(error);
            }
        });

        ws.on('close', () => {
            console.log('close');
        });

        ws.on('error', (error) => {
            console.log(error);
        });
    });
    return wss;
}

now at the server initilization just call the function from a different file现在在服务器初始化时,只需从不同的文件中调用 function

... ...

const {initSocketEvents}  = require("./socket-handler") 
const wss = new WebSocketServer({ noServer: true });
initSocketEvents(was);

... ...

everything stays the same except the fact its way much easier to test it now at the test file一切都保持不变,除了现在在测试文件中测试它的方式更容易

const {initSocketEvents}  = require("./socket-handler") 
const { assert } = require('console');
const { EventEmitter } = require('events');
class MyTestWebSocket extends EventEmitter { }
const mockWSS = new MyTestWebSocket()
initSocketEvents(mockWSS)
mockWSS.emit('connection', mockWSS)
assert(mockWSS.listenerCount('connection')===1)
assert(mockWSS.listenerCount('message')===1)
assert(mockWSS.listenerCount('close')===1)
assert(mockWSS.listenerCount('error')===1)

now it should be straightforward to separate each listener's logic and inject it outside the function and then assert the desired logic.现在应该直接分离每个侦听器的逻辑并将其注入 function 之外,然后断言所需的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM