title: TDD/ testing with streams in NodeJS
body: <p>I've been trying to find a reasonable way to test code that uses streams. Has anyone found a reasonable way/ framework to help testing code that uses streams in nodejs?</p>
  
  <p>For example:</p>
  
  <pre><code>var fs = require('fs'),
      request = require('request');
  
  module.exports = function (url, path, callback) {
    request(url)
      .pipe(fs.createWriteStream(path))
      .on('finish', function () {
        callback();
      });
  };
  </code></pre>
  
  <p>My current way of testing this type of code either involves simplifying the code with streams so much that I can abstract it out to a non-tested chunk of code or by writing something like this:</p>
  
  <pre><code>var rewire = require('rewire'),
      download = rewire('../lib/download'),
      stream = require('stream'),
      util = require('util');
  
  describe('download', function () {
    it('should download a url', function (done) {
      var fakeRequest, fakeFs, FakeStream;
  
      FakeStream = function () {
        stream.Writable.call(this);
      };
  
      util.inherits(FakeStream, stream.Writable);
  
      FakeStream.prototype._write = function (data, encoding, cb) {
        expect(data.toString()).toEqual("hello world")
        cb();
      };
  
      fakeRequest = function (url) {
        var output = new stream.Readable();
  
        output.push("hello world");
        output.push(null);
  
        expect(url).toEqual('http://hello');
  
        return output;
      };
  
      fakeFs = {
        createWriteStream: function (path) {
          expect(path).toEqual('hello.txt');
          return new FakeStream();
        }
      };
  
      download.__set__('fs', fakeFs);
      download.__set__('request', fakeRequest);
  
      download('http://hello', 'hello.txt', function () {
        done();
      });
  
    });
  });
  </code></pre>
  
  <p>Has anyone come up with more elegant ways of testing streams?</p>