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

xienkqul  于 2022-11-11  发布在  Jest
关注(0)|答案(1)|浏览(256)

我正在尝试找出如何为使用ws库的WebSocket服务器编写单元测试用例。我确实通过了jest-websocket-mock,但我认为这是针对基于浏览器的API,我想使用JEST测试服务器。
基本代码: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);
  }); 
});

有人能帮助我如何测试原始服务器吗?

q8l4jmvw

q8l4jmvw1#

您需要创建某种依赖注入机制,例如,将所有套接字初始化逻辑移动到一个单独的函数中

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;
}

现在,在服务器初始化时,只需从不同的文件中调用函数
...

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

...
一切都保持不变,除了它的方式更容易测试它现在在测试文件

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)

现在应该可以直接分离每个侦听器的逻辑并将其注入到函数之外,然后Assert所需的逻辑。

相关问题