单元测试Node.js和WebSockets(Socket.io)

时间:2013-03-19 19:57:12

标签: node.js unit-testing websocket socket.io

有没有人可以使用WebSockets(Socket.io)为Node.js提供坚如磐石的简单单元测试?

我正在为Node.js使用socket.io,并且已经查看了socket.io-client,以便在测试中建立与服务器的客户端连接。但是,我似乎错过了一些东西。

在下面的例子中,“工作......”永远不会打印出来。

var io = require('socket.io-client')
, assert = require('assert')
, expect = require('expect.js');

describe('Suite of unit tests', function() {

    describe('First (hopefully useful) test', function() {

        var socket = io.connect('http://localhost:3001');
        socket.on('connect', function(done) {
            console.log('worked...');
            done();
        });

        it('Doing some things with indexOf()', function() {
            expect([1, 2, 3].indexOf(5)).to.be.equal(-1);
            expect([1, 2, 3].indexOf(0)).to.be.equal(-1);
        });

    });
});

相反,我只是得到:

  Suite of unit tests
    First (hopefully useful) test
      ✓ Doing some things with indexOf() 


  1 test complete (26 ms)

有什么建议吗?

6 个答案:

答案 0 :(得分:60)

在进一步戳戳和刺激之后,我在http://blog.foundry376.com/2012/09/connecting-to-a-socket-io-server-from-node-js-unit-tests找到了一些非常有用的信息。在作者的例子中,他指出了在“before *”钩子中建立套接字监听器的关键步骤。此示例有效(假设服务器正在侦听localhost:3001处的套接字连接)

var io = require('socket.io-client')
, assert = require('assert')
, expect = require('expect.js');

describe('Suite of unit tests', function() {

    var socket;

    beforeEach(function(done) {
        // Setup
        socket = io.connect('http://localhost:3001', {
            'reconnection delay' : 0
            , 'reopen delay' : 0
            , 'force new connection' : true
        });
        socket.on('connect', function() {
            console.log('worked...');
            done();
        });
        socket.on('disconnect', function() {
            console.log('disconnected...');
        })
    });

    afterEach(function(done) {
        // Cleanup
        if(socket.connected) {
            console.log('disconnecting...');
            socket.disconnect();
        } else {
            // There will not be a connection unless you have done() in beforeEach, socket.on('connect'...)
            console.log('no connection to break...');
        }
        done();
    });

    describe('First (hopefully useful) test', function() {

        it('Doing some things with indexOf()', function(done) {
            expect([1, 2, 3].indexOf(5)).to.be.equal(-1);
            expect([1, 2, 3].indexOf(0)).to.be.equal(-1);
            done();
        });

        it('Doing something else with indexOf()', function(done) {
            expect([1, 2, 3].indexOf(5)).to.be.equal(-1);
            expect([1, 2, 3].indexOf(0)).to.be.equal(-1);
            done();
        });

    });

});

我发现在beforeEach,socket.on('connect'...)监听器中放置done()对于建立连接至关重要。例如,如果你在侦听器中注释掉done(),然后将其添加到一个范围内(就在退出beforeEach之前),你会看到“没有连接到中断...”的消息而不是“断开连接...” 。“ 信息。像这样:

beforeEach(function(done) {
    // Setup
    socket = io.connect('http://localhost:3001', {
        'reconnection delay' : 0
        , 'reopen delay' : 0
        , 'force new connection' : true
    });
    socket.on('connect', function() {
        console.log('worked...');
        //done();
    });
    socket.on('disconnect', function() {
        console.log('disconnected...');
    });
    done();
});

我是Mocha的新手,因此可能有一个非常明显的理由要求在套接字范围内放置done()。希望这个小细节可以让我的鞋子中的其他人免于拉毛。

对我来说,上面的测试(正确确定了done()的范围)输出:

  Suite of unit tests
    First (hopefully useful) test
      ◦ Doing some things with indexOf(): worked...
      ✓ Doing some things with indexOf() 
disconnecting...
disconnected...
      ◦ Doing something else with indexOf(): worked...
      ✓ Doing something else with indexOf() 
disconnecting...
disconnected...


  2 tests complete (93 ms)

答案 1 :(得分:7)

在此处提供已接受答案的扩展。具有基本的客户端到服务器通信,可用作其他未来测试的样板。使用mocha,chai和expect。

var io = require('socket.io-client')
  , io_server = require('socket.io').listen(3001);

describe('basic socket.io example', function() {

  var socket;

  beforeEach(function(done) {
    // Setup
    socket = io.connect('http://localhost:3001', {
      'reconnection delay' : 0
      , 'reopen delay' : 0
      , 'force new connection' : true
      , transports: ['websocket']
    });

    socket.on('connect', () => {
      done();
    });

    socket.on('disconnect', () => {
      // console.log('disconnected...');
    });
  });

  afterEach((done) => {
    // Cleanup
    if(socket.connected) {
      socket.disconnect();
    }
    io_server.close();
    done();
  });

  it('should communicate', (done) => {
    // once connected, emit Hello World
    io_server.emit('echo', 'Hello World');

    socket.once('echo', (message) => {
      // Check that the message matches
      expect(message).to.equal('Hello World');
      done();
    });

    io_server.on('connection', (socket) => {
      expect(socket).to.not.be.null;
    });
  });

});

答案 2 :(得分:4)

自己处理回调和承诺可能很困难,而且非平凡的例子很快就会变得非常复杂和难以阅读。

有一个名为 socket.io-await-test 的工具可通过 NPM 使用,它允许您在测试中暂停/等待,直到使用 await 关键字触发事件。

  describe("wait for tests", () => {
    it("resolves when a number of events are received", async () => {
        const tester = new SocketTester(client);
        const pongs = tester.on('pong');
        
        client.emit('ping', 1);
        client.emit('ping', 2);
        await pongs.waitForEvents(2) // Blocks until the server emits "pong" twice. 

        assert.equal(pongs.get(0), 2)
        assert.equal(pongs.get(1), 3)
    })
})

答案 3 :(得分:2)

我遇到了这个问题:如果您不知道服务器响应多长时间,如何使用“socket.io-client”进行单元测试?

我已经使用 mocha chai 解决了这个问题:

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

答案 4 :(得分:2)

查看基于承诺良好实践样板解决方案。 您可以使用它测试服务器的整个io事件,而不会费力。 您只需要复制样板测试并根据需要添加自己的代码即可。

在GitHub上查看存储库以获取完整的源代码。

https://github.com/PatMan10/testing_socketIO_server

const io = require("socket.io-client");
const ev = require("../utils/events");
const logger = require("../utils/logger");

// initSocket returns a promise
// success: resolve a new socket object
// fail: reject a error
const initSocket = () => {
  return new Promise((resolve, reject) => {
      // create socket for communication
      const socket = io("localhost:5000", {
        "reconnection delay": 0,
        "reopen delay": 0,
        "force new connection": true
      });

      // define event handler for sucessfull connection
      socket.on(ev.CONNECT, () => {
        logger.info("connected");
        resolve(socket);
      });

      // if connection takes longer than 5 seconds throw error
      setTimeout(() => {
        reject(new Error("Failed to connect wihtin 5 seconds."));
      }, 5000);
    }
  );
};


// destroySocket returns a promise
// success: resolve true
// fail: resolve false
const destroySocket = socket => {
  return new Promise((resolve, reject) => {
    // check if socket connected
    if (socket.connected) {
      // disconnect socket
      logger.info("disconnecting...");
      socket.disconnect();
      resolve(true);
    } else {
      // not connected
      logger.info("no connection to break...");
      resolve(false);
    }
  });
};

describe("test suit: Echo & Bello", () => {
  test("test: ECHO", async () => {
    // create socket for communication
    const socketClient = await initSocket();

    // create new promise for server response
    const serverResponse = new Promise((resolve, reject) => {
      // define a handler for the test event
      socketClient.on(ev.res_ECHO, data4Client => {
        //process data received from server
        const { message } = data4Client;
        logger.info("Server says: " + message);

        // destroy socket after server responds
        destroySocket(socketClient);

        // return data for testing
        resolve(data4Client);
      });

      // if response takes longer than 5 seconds throw error
      setTimeout(() => {
        reject(new Error("Failed to get reponse, connection timed out..."));
      }, 5000);
    });

    // define data 4 server
    const data4Server = { message: "CLIENT ECHO" };

    // emit event with data to server
    logger.info("Emitting ECHO event");
    socketClient.emit(ev.com_ECHO, data4Server);

    // wait for server to respond
    const { status, message } = await serverResponse;

    // check the response data
    expect(status).toBe(200);
    expect(message).toBe("SERVER ECHO");
  });

  test("test BELLO", async () => {
    const socketClient = await initSocket();
    const serverResponse = new Promise((resolve, reject) => {
      socketClient.on(ev.res_BELLO, data4Client => {
        const { message } = data4Client;
        logger.info("Server says: " + message);
        destroySocket(socketClient);
        resolve(data4Client);
      });

      setTimeout(() => {
        reject(new Error("Failed to get reponse, connection timed out..."));
      }, 5000);
    });

    const data4Server = { message: "CLIENT BELLO" };
    logger.info("Emitting BELLO event");
    socketClient.emit(ev.com_BELLO, data4Server);

    const { status, message } = await serverResponse;
    expect(status).toBe(200);
    expect(message).toBe("SERVER BELLO");
  });
});

----脚注----

根据如何设置服务器环境,您可能会遇到在同一项目中同时运行的socket.io和socket.io-client之间的环境冲突。在这种情况下,最好将项目分为“测试客户端”和服务器。如果您遇到此问题,请在回购下方查看。

https://github.com/PatMan10/testing_socketIO_server_v2

答案 5 :(得分:1)

在OP的代码中,

socket.on('connect', function(done) {
    console.log('worked...');
    done();
});

done应用于错误的回调。应该从socket.on回调中删除它,并将其添加到Mocha的it块回调中:

it('First (hopefully useful) test', function (done) {
  var socket = io.connect('http://localhost:3001');
  socket.on('connect', function () {
    console.log('worked...');
    done();
  });
});

完整示例

现有的答案很好,但没有显示服务器最终正在测试。这是带有console.log的完整版本,用于说明发生了什么。解释如下。

src/server.js

const express = require("express");

const createServer = (port=3000) => {
  const app = express();
  const http = require("http").Server(app);
  const io = require("socket.io")(http);
  
  io.on("connection", socket => {
    console.log("[server] user connected");
    
    socket.on("message", msg => {
      console.log(`[server] received '${msg}'`);
      socket.emit("message", msg);
    });
    socket.on("disconnect", () => {
      console.log("[server] user disconnected");
    });
  });
  
  http.listen(port, () =>
    console.log(`[server] listening on port ${port}`)
  );
  return {
    close: () => http.close(() => 
      console.log("[server] closed")
    )
  };
};
module.exports = {createServer};

test/server.test.js

const {expect} = require("chai");
const io = require("socket.io-client");
const {createServer} = require("../src/server");
const socketUrl = "http://localhost:3000";

describe("server", function () {
  this.timeout(3000);
  
  let server;
  let sockets;
  beforeEach(() => {
    sockets = [];
    server = createServer();
  });
  afterEach(() => {
    sockets.forEach(e => e.disconnect())
    server.close();
  });
  
  const makeSocket = (id=0) => {
    const socket = io.connect(socketUrl, {
      "reconnection delay": 0,
      "reopen delay": 0,
      "force new connection": true,
      transports: ["websocket"],
    });
    socket.on("connect", () => {
      console.log(`[client ${id}] connected`);
    });
    socket.on("disconnect", () => {
      console.log(`[client ${id}] disconnected`);
    });
    sockets.push(socket);
    return socket;
  };
  
  it("should echo a message to a client", done => {
    const socket = makeSocket();
    socket.emit("message", "hello world");
    socket.on("message", msg => {
      console.log(`[client] received '${msg}'`);
      expect(msg).to.equal("hello world");
      done();
    });
  });
  
  it("should echo messages to multiple clients", () => {
    const sockets = [...Array(5)].map((_, i) => makeSocket(i));
    
    return Promise.all(sockets.map((socket, id) =>
      new Promise((resolve, reject) => {
        const msgs = [..."abcd"].map(e => e + id);
        msgs.slice().forEach(e => socket.emit("message", e));
      
        socket.on("message", msg => {
          console.log(`[client ${id}] received '${msg}'`);
          expect(msg).to.equal(msgs.shift());
          
          if (msgs.length === 0) {
            resolve();
          }
        });
      })
    ));
  });
});

总而言之,服务器导出一个函数,该函数允许从头开始创建服务器应用程序,从而允许每个it块都是幂等的,并避免在测试之间进行服务器状态的处理(否则假设服务器上没有持久性)。创建应用将返回带有close函数的对象。在每次测试中,必须为每个套接字调用socket.disconnect(),以免超时。

鉴于这些要求,测试套件遵循以下每次测试设置/拆卸工作流程:

let server;
let sockets;
beforeEach(() => {
  sockets = [];
  server = createServer();
});
afterEach(() => {
  sockets.forEach(e => e.disconnect())
  server.close();
});

makeSocket是一个可选的助手,可以减少连接和断开套接字客户端的重复样板。它确实会在sockets数组上产生副作用,以便稍后进行清理,但这是从it块的角度来看的实现细节。测试块不应触摸serversockets变量,尽管其他工作流程可能根据需要而定。关键要点是测试用例的幂等性以及在每个测试用例之后关闭所有连接。

客户端上socket.connect对象上的

选项使您可以选择套接字的传输方式和行为。 "force new connection": true为每个套接字创建一个新的Manager,而不是重用现有的套接字,并且transports: ["websocket"]从长轮询中立即升级到WS协议。

在回调中完成所有工作后使用it("should ... ", done => { /* tests */ });并调用done()或返回promise(并将done参数省略到it回调中)。上面的示例显示了两种方法。


在此帖子中使用:

  • node:12.19.0
  • chai:4.2.0
  • express:4.16.4
  • mocha:5.2.0
  • socket.io:2.2.0
  • socket.io-client:2.2.0