用socket.io npm编写聊天应用程序的单元测试

时间:2019-12-01 09:08:45

标签: unit-testing sockets events mocking jestjs

我试图编写单元测试并创建一个模拟套接字对象,当我运行测试时,它通过了,但是没有碰到任何我的应用程序功能。它不包含任何功能。帮助我为我的应用编写适当的单元测试。

app.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`);
});



我的应用测试

const io = require('../server/app.js');
const MockedSocket = require('socket.io-mock');
//let socket = new MockedSocket();

//const  SocketMock = 'socket.io-mock';
const { expect } = require('chai');

describe('socket tests', function() {
  it('Sockets should be able to talk to each other without a server', function(done){
    let socket = new MockedSocket();
    socket.on('message', function (message) {
      expect(message).to.equal('Hello World!');
    });
    socket.socketClient.emit('message', 'Hello World!');
    jest.setTimeout(30000);
    done();
  });

  it('it console logs when user is connect', () => {
    let socket = new MockedSocket();
    let username = 'test';
    socket.on('user name', function(data){
      socket.username = data.username;
      socket.socketClient.emit('new user', username);
      expect(data).to.equal('test joined the chat!');

    });

  });

});

0 个答案:

没有答案