如何在NodeJS中模拟流 [英] How to mock streams in NodeJS
问题描述
我正在尝试对大量处理流的node-js模块之一进行单元测试.我正在尝试模拟流(我将要写入的流),因为在我的模块中,我想触发".on('data/end)"侦听器.本质上,我希望能够执行以下操作:
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();
这会执行,但是我执行推送后就不会触发"on"事件(并且.close()无效).
我在流上可以找到的所有指南都使用"fs"或"net"库作为创建新流的基础( https://github.com/substack/stream-handbook ),或者他们使用sinon对其进行了模拟,但模拟过程非常漫长,非常迅速.
有没有提供这样的虚拟流的好方法?
我应该使用".emit(< event> ;,< data>);"而不是使用Push.
我的模拟代码现在可以正常工作,并且看起来像:
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');
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?
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');
这篇关于如何在NodeJS中模拟流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!