Search code examples
node.jsunit-testingnode.js-stream

How to mock streams in NodeJS


I'm attempting to unit test one of my node-js modules which deals heavily in streams. I'm trying to mock a stream (that I will write to), as within my module I have ".on('data/end)" listeners that I would like to trigger. Essentially I want to be able to do something like this:

var mockedStream = new require('stream').readable();

mockedStream.on('data', function withData('data') {
  console.dir(data);
});

mockedStream.on('end', function() { 
  console.dir('goodbye');
});

mockedStream.push('hello world');
mockedStream.close();

This executes, but the 'on' event never gets fired after I do the push (and .close() is invalid).

All the guidance I can find on streams uses the 'fs' or 'net' library as a basis for creating a new stream (https://github.com/substack/stream-handbook), or they mock it out with sinon but the mocking gets very lengthy very quicky.

Is there a nice way to provide a dummy stream like this?


Solution

  • Instead of using Push, I should have been using ".emit(<event>, <data>);"

    My mock code now works and looks like:

    var mockedStream = new require('stream').Readable();
    mockedStream._read = function(size) { /* do nothing */ };
    
    myModule.functionIWantToTest(mockedStream); // has .on() listeners in it
    
    mockedStream.emit('data', 'Hello data!');
    mockedStream.emit('end');