【问题标题】:Testing node tcp server with mocha使用 mocha 测试节点 tcp 服务器
【发布时间】:2013-12-21 23:24:29
【问题描述】:

我有一个 tcp 服务器,我想用 mocha 进行测试:

// Start the server
require('net').createServer(function (socket) {
  // Handle incoming data
  socket.on('data', function (data) {
     ... some stuff
     socket.write("reply with some err message if any");
  });
});

我通常用expressjs为HTTP Rest API开发node应用,并使用grunt-express-server模块,例如:

grunt.registerTask('validate', [
    'express:dev',
    'mochaTest',
    'express:dev:stop'
]);

这会运行 express 服务器,运行测试并停止 express 服务器。
有没有同样的东西可以测试 tcp server 吗?

【问题讨论】:

    标签: node.js unit-testing testing tcp mocha.js


    【解决方案1】:

    当然是。你可以用 Mocha 测试你想要的任何东西。像下面这样的东西应该可以工作:

    describe('Test tcp server', function () {
    
        it('Should reply with some err message if any', function (done) {
    
            // Set up a client and connect to port 31337 (or whatever port you use)
            var client = net.connect({ port: 31337 },
                function() {
                    // Send some data
                    client.write('Let's send this data!');
                }
            );
    
            // When data is returned from server
            client.on('data', function(data) {
                // Let's make sure data equals the correct message
                data.should.equal('reply with some err message if any');
                client.end();
                done();
            }); 
    
        });
    
    });
    

    【讨论】:

    • 谢谢,这真的很有帮助,但是如何在测试套件开始时直接启动和停止服务器,并在所有测试完成后停止它?任何与用于测试快速服务器的 grunt 模块类似的模块?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    相关资源
    最近更新 更多