gruberb gruberb - 4 years ago 136
Node.js Question

How can I mock the return value of Nodes net library functions?

I have a Node module where I try to connect to a host with:

const testConnection = net.createConnection(port, hostname);

testConnection.on('connect', () => {
// connected

testConnection.on('error', (err) => {
// error

I am using Sinon to test the method like this:

sinon.stub(net, 'createConnection', (port, hostname) => {
return {
on: (string, cb) => {
switch(string) {
case 'connect':
return cb;
case 'error':
return cb;
case 'close':
return cb;

const testConnection = net.createConnection(10, 'hostname');
testConnection.on('error', () => {
console.log('here I am');

But I cannot wrap my head around how I should no stub/mock or fake-call the on-method so it returns an error!

Am I missing something here?

Answer Source

I'd stub createConnection return value with a fake EventEmitter instance:

const EventEmitter = require('events');
const fakeEE = new EventEmitter();
sinon.stub(net, 'createConnection', (port, hostname) => fakeEE);

// require your code

// emit events
fakeEE.emit('error', new Error('Smth bad happened'));

// observe the result
// e.g. expect(something).toBeCalled();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download