如何编写测试来验证我的应用程序是否通过 dgram 绑定(bind)到特定的 UDP 端口?下面是我想要测试的代码片段:
var dgram = require('dgram');
var socket_json = dgram.createSocket('udp4');
var socket_syslog = dgram.createSocket('udp4');
socket_json.bind(6371);
socket_syslog.bind(6370);
我正在尝试使用 Mocha 和 Chai 进行测试:
var expect = require("chai").expect;
var sawyer = require("../server.js");
describe("Sawyer", function() {
it("should bind to UDP port 6370", function() {
// some kind of expect statement here
});
it("should bind to UDP port 6371", function() {
// some kind of expect statement here
});
});
非常感谢任何帮助!
最佳答案
根据documentation ,将在 socket
上发出 error
事件,或者如果 socket.bind()
失败,可能会引发错误。
因此,您可以监视这两件事,并向 socket.bind()
添加一个回调参数(或者在 socket
上添加一个 listening
事件处理程序,这就是 socket.bind()
为您所做的事情),绑定(bind)完成后将调用该回调参数。
示例:
socket_json.on('error', function(err) {
console.log('Socket error: ' + err.message);
}).on('listening', function() {
console.log('Successfully bound JSON socket!');
});
try {
socket_json.bind(6371);
} catch (ex) {
console.log('Failed to bind JSON socket: ' + ex.message);
}
关于node.js - 在 Node.js 中测试 dgram 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30147274/