2015-10-19 221 views
0

我正在嘗試使用socket.io製作簡單的聊天應用程序。手動它工作正常(通過瀏覽器本地主機:3000 /),但我想編寫單元測試來驗證服務器的邏輯。我不知道使用哪些工具/庫進行測試。如何編寫測試:Socket.io應用程序單元測試

這裏是我的節點服務器代碼:

index.js

var app = require('express')(); 
var http = require('http').Server(app); 
var io = require('socket.io')(http); 

var socketCount = 0; 

http.listen(3000, function(){ 
    console.log('listening on *:3000'); 
}); 

app.get('/', function(req, res){ 
    res.sendFile(__dirname + '/index.html'); 
}); 

io.on('connection', function(socket) { 

    socketCount++; 

    console.log('new user connected'); 

    // Let all sockets know how many are connected 
    io.emit('users connected', socketCount); 

    socket.on('disconnect', function(){ 
    // Decrease the socket count on a disconnect, emit 
    socketCount--; 
    io.emit('users connected', socketCount); 
    }); 

    socket.on('chat message', function(msg){ 
    // New message added, broadcast it to all sockets 
    io.emit('chat message', msg); 
    }); 

}); 

這裏是我的html頁面:

文件:index.html的

<html> 
... 
<body> 
    <ul id="messages"></ul> 
    <div class='footer'> 
     <div id="usersConnected"></div> 
     <form action=""> 
     <input id="m" autocomplete="off" /><button>Send</button> 
     </form> 
    </div> 
    </body> 
    ... 
    <script> 
    $(document).ready(function(){ 
     $('#messages').val(''); 
     var socket = io(); 

     $('form').submit(function(){ 
      socket.emit('chat message', $('#m').val()); 
      $('#m').val(''); 
      return false; 
     }); 

     // New message emitted, add it to our list of current messages 
     socket.on('chat message', function(msg){ 
      $('#messages').append($('<li>').text(msg)); 
     }); 

     // New socket connected, display new count on page 
     socket.on('users connected', function(count){ 
      $('#usersConnected').html('Users connected: ' + count); 
     }); 
    }); 
    </script> 
</html> 

感謝。

回答

0

我有這個問題:如果你不知道服務器需要多長時間做出響應,如何用「socket.io-client」做單元測試?

我已經解決了這樣使用摩卡

var os = require('os'); 
var should = require("chai").should(); 
var socketio_client = require('socket.io-client'); 

var end_point = 'http://' + os.hostname() + ':8081'; 
var opts = {forceNew: true}; 

describe("async test with socket.io", function() { 
this.timeout(10000); 

it('Response should be an object', function (done) { 
    setTimeout(function() { 
     var socket_client = socketio_client(end_point, opts); 

     socket_client.emit('event', 'ABCDEF'); 

     socket_client.on('event response', function (data) { 
      data.should.be.an('object'); 
      socket_client.disconnect(); 
      done(); 
     }); 

     socket_client.on('event response error', function (data) { 
      console.error(data); 
      socket_client.disconnect(); 
      done(); 
      }); 
     }, 4000); 
    }); 
});