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?
Building on @flacnut 's answer, I did this (in NodeJS 12+) using
Readable.from()
to construct a stream preloaded with data (a list of filenames):In my case, I wanted to mock the stream of filenames returned by fast-glob.stream:
In the function being tested:
Works like a charm!
Instead of using Push, I should have been using ".emit(<event>, <data>);"
My mock code now works and looks like:
There's a simpler way:
stream.PassThrough
I've just found Node's very easy to miss
stream.PassThrough
class, which I believe is what you're looking for.From Node docs:
link to docs
The code from the question, modified:
mockedStream.push()
works too but as aBuffer
so you'll might want to do:console.dir(d.toString());
The accept answer is only partially correct. If all you need is events to fire, using
.emit('data', datum)
is okay, but if you need to pipe this mock stream anywhere else it won't work.Mocking a Readable stream is surprisingly easy, requiring only the Readable lib.
Now you can pipe this stream wherever and 'data' and 'end' will fire.
Another example from the node docs: https://nodejs.org/api/stream.html#stream_an_example_counting_stream