Skip to content

Instantly share code, notes, and snippets.

@Farenheith
Last active February 22, 2020 15:10
Show Gist options
  • Save Farenheith/f8b6a4c4916384350d833c6f9d001d7b to your computer and use it in GitHub Desktop.
Save Farenheith/f8b6a4c4916384350d833c6f9d001d7b to your computer and use it in GitHub Desktop.
An example of a nasty stream test
import { expect } from 'chai';
import { stub } from 'sinon';
import * as zlib from 'zlib';
import { streamExample } from '../src/stream-example';
import { Readable, Writable } from 'stream';
describe('streamExample()', () => {
let data: any[];
let writable: Writable;
beforeEach(() => {
data = [];
writable = new Writable({
write(chunk: Buffer, _encoding: string, next: Function) {
data.push(chunk.toString());
next();
},
});
stub(zlib, 'createGzip').returns(writable as any);
});
it('should pipe the given stream to a gzip writer', async () => {
let index = 0;
const stream = new Readable({
read() {
if (index < 3) {
index++;
this.push(`value${index}`);
} else {
this.push(null);
}
}
});
stub(stream, 'pipe').callThrough();
const result = streamExample(stream);
await new Promise((resolve, reject) => {
result.on('finish', resolve);
result.on('error', reject);
});
expect(zlib.createGzip).to.have.been.calledOnceWithExactly();
expect(stream.pipe).to.have.been.calledOnceWithExactly(writable);
expect(data).to.be.eql(['value1', 'value2', 'value3']);
});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment