I am working on a project chat app in java script using socket.io back end only, And I want to write unit test using jest ,npm .
(我正在仅使用socket.io后端以Java脚本开发项目聊天应用程序,并且我想使用jest,npm编写单元测试。)
And I got trouble on 1. how to mock socket.io with jest 2. how to test console.log results(我遇到了麻烦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
');
});
afterEach(() => {
jest.clearAllMocks();
});
the code I want to test is the following , app.js and chat.js
(我要测试的代码如下,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
`);
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
`);
});
But more features will be added like authontication, attchement, private chat ...
this file is sent to be checked
(该文件已发送以供检查)
ask by Meron Alemu translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…