我有一个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");
});
});
我通常用HTTP Rest API的expressjs开发节点应用程序,并使用grunt-express-server模块,例如:
grunt.registerTask('validate', [
'express:dev',
'mochaTest',
'express:dev:stop'
]);
运行快速服务器,运行测试并停止快速服务器 是否有同样的东西来测试tcp服务器?
答案 0 :(得分:3)
当然可以。你可以用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();
});
});
});