I'm trying to create a dummy socket for use in some of my tests
var net = require("net"); var s = new net.Socket(); s.on("data", function(data) { console.log("data received:", data); }); s.write("hello!");
Getting this error
Error: This socket is closed.
I've also tried creating the socket with
var s = new net.Socket({allowHalfOpen: true});
What am I doing wrong?
For reference, the complete test looks like this
it("should say hello on connect", function(done) { var socket = new net.Socket(); var client = Client.createClient({socket: socket}); socket.on("data", function(data){ assert.equal("hello", data); done(); }); client.connect(); // writes "hello" to the socket });
I don't think the server is put into listening state. This what I use..
// server require('net').createServer(function (socket) { console.log("connected"); socket.on('data', function (data) { console.log(data.toString()); }); }) .listen(8080); // client var s = require('net').Socket(); s.connect(8080); s.write('Hello'); s.end();
Client only..
var s = require('net').Socket(); s.connect(80, 'google.com'); s.write('GET http://www.google.com/ HTTP/1.1\n\n'); s.on('data', function(d){ console.log(d.toString()); }); s.end();
Try this.
The production code app.js
:
var net = require("net"); function createSocket(socket){ var s = socket || new net.Socket(); s.write("hello!"); } exports.createSocket = createSocket;
The test code: test.js
: (Mocha)
var sinon = require('sinon'), assert = require('assert'), net = require('net'), prod_code=require('./app.js') describe('Example Stubbing net.Socket', function () { it("should say hello on connect", function (done) { var socket = new net.Socket(); var stub = sinon.stub(socket, 'write', function (data, encoding, cb) { console.log(data); assert.equal("hello!", data); done(); }); stub.on = socket.on; prod_code.createSocket(socket); }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With