如何在javascript中使用jest npm模拟soket.io

如何在javascript中使用jest npm模拟soket.io,javascript,unit-testing,socket.io,jestjs,chat,Javascript,Unit Testing,Socket.io,Jestjs,Chat,我正在使用socket.io后端开发java脚本中的项目聊天应用程序,我想使用jest、npm编写单元测试。我在这方面遇到了麻烦 1.如何用笑话模拟socket.io 2.如何测试console.log结果 console.log = jest.fn(); test ('check chat status', () => { expect(console.log.mock.calls.length).toBe(0); socket.on('connect'); expect

我正在使用socket.io后端开发java脚本中的项目聊天应用程序,我想使用jest、npm编写单元测试。我在这方面遇到了麻烦 1.如何用笑话模拟socket.io 2.如何测试console.log结果

console.log = jest.fn();


test ('check chat status', () => {
  expect(console.log.mock.calls.length).toBe(0);
  socket.on('connect');
  expect(console.log.mock.calls.length).toBe(1);
  expect(console.log.mock.calls[0][0]).toBe('Chat started\n');
});

afterEach(() => {
  jest.clearAllMocks();
});
我想测试的代码如下:app.js和chat.js

'use strict';

const io = require('socket.io')(3000);

io.on('connection', (socket) => {
  socket.on('username', (data) => {
    socket.username = data.username;
    console.log(`${socket.username} joined the chat!`);

    socket.broadcast.emit('new user', socket.username);
  });

  socket.on('message', (data) => {
    socket.broadcast.emit('message', {user: socket.username, message: data});
  });

  socket.on('disconnect', () => {
    console.log(`User left the chat`);
  });
});


chat.js 
'use strict';

const io = require('socket.io-client');
const socket = io.connect('http://localhost:3000');

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let username;

socket.on('connect', () => {
  console.log(`Chat started\n`);

  rl.question('What is your name? ', (answer) => {
    username = answer;
    socket.emit('username', {username: username});
  });
});

rl.on('line', (message) => {
  socket.emit('message', message);
});

socket.on('message', (data) => {
  console.log(`${data.user}: ${data.message}`);
});

socket.on('new user', (data) => {
  console.log(`${data} joined the chat\n`);
});

But more features will be added like authontication, attchement, private chat ...

此文件发送以供检查

请提供您想要测试的代码。如果您尝试过,我没有使用过它,但可能会有所帮助。否则,看看这个也许可以回答你的问题: