我正在尝试对我的一个 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 模拟它,但模拟变得非常冗长非常快.
有没有一种很好的方法来提供这样的虚拟流?
最佳答案
有一个更简单的方法: stream.PassThrough
我刚刚发现 Node 很容易被忽略 stream.PassThrough
类,我相信这就是您要找的。p>
来自 Node docs :
The stream.PassThrough class is a trivial implementation of a Transform stream that simply passes the input bytes across to the output. Its purpose is primarily for examples and testing...
问题中的代码,已修改:
const { PassThrough } = require('stream');
const mockedStream = new PassThrough(); // <----
mockedStream.on('data', (d) => {
console.dir(d);
});
mockedStream.on('end', function() {
console.dir('goodbye');
});
mockedStream.emit('data', 'hello world');
mockedStream.end(); // <-- end. not close.
mockedStream.destroy();
mockedStream.push()
也可以,但作为 Buffer
所以你可能想做:console.dir(d.toString());
关于node.js - 如何在 NodeJS 中模拟流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33141012/