FlushWritable.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * FlushWritable
  3. * Copyright 2014 Tom Frost
  4. */
  5. var FlushWritable = require('../lib/FlushWritable'),
  6. Readable = require('stream').Readable,
  7. util = require('util'),
  8. should = require('should');
  9. function TestWritable() {
  10. FlushWritable.call(this);
  11. }
  12. util.inherits(TestWritable, FlushWritable);
  13. TestWritable.prototype._flush = function(cb) {
  14. this.flushCalled = true;
  15. setTimeout(function() {
  16. cb(this.err);
  17. }.bind(this), 10);
  18. };
  19. TestWritable.prototype._write = function(data, encoding, cb) {
  20. cb();
  21. };
  22. function TestReadable() {
  23. this.i = 0;
  24. Readable.call(this);
  25. }
  26. util.inherits(TestReadable, Readable);
  27. TestReadable.prototype._read = function() {
  28. if (this.i++ === 2)
  29. this.push(null);
  30. else
  31. this.push('foo');
  32. };
  33. describe('FlushWritable', function() {
  34. it('should call _flush prior to emitting finish', function(done) {
  35. var r = new TestReadable(),
  36. w = new TestWritable(),
  37. finished = false;
  38. w.on('finish', function() {
  39. finished = true;
  40. });
  41. r.pipe(w);
  42. setTimeout(function() {
  43. w.should.have.property('flushCalled');
  44. finished.should.eql(false);
  45. setTimeout(function() {
  46. finished.should.eql(true);
  47. done();
  48. }, 10);
  49. }, 5);
  50. });
  51. it('should emit error instead of finish for errors in cb', function(done) {
  52. var r = new TestReadable(),
  53. w = new TestWritable(),
  54. finished = false,
  55. errored = false;
  56. w.on('finish', function() {
  57. finished = true;
  58. });
  59. w.on('error', function() {
  60. errored = true;
  61. });
  62. w.err = new Error('bar');
  63. r.pipe(w);
  64. setTimeout(function() {
  65. finished.should.eql(false);
  66. errored.should.eql(true);
  67. done();
  68. }, 15);
  69. });
  70. it('should finish immediately if no _flush is defined', function(done) {
  71. var r = new TestReadable(),
  72. w = new TestWritable(),
  73. finished = false;
  74. w.on('finish', function() {
  75. finished = true;
  76. });
  77. w._flush = undefined;
  78. r.pipe(w);
  79. setTimeout(function() {
  80. finished.should.eql(true);
  81. done();
  82. }, 5);
  83. });
  84. });