Last active
February 22, 2020 16:38
-
-
Save Farenheith/9cc361cf2a7975bac2503f29fa930db2 to your computer and use it in GitHub Desktop.
An example of tests of a function with stream and promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { expect } from 'chai'; | |
import { stub, SinonStub, match } from 'sinon'; | |
import * as zlib from 'zlib'; | |
import { notSoSimpleStreamExample } from '../src/not-so-simple-stream-example'; | |
import { ObjectReadableMock } from 'stream-mock'; | |
describe('notSoSimpleStreamExample()', () => { | |
let data: any[] = []; | |
let gzip: SinonStub<any, any>; | |
beforeEach(() => { | |
data = []; | |
gzip = stub(zlib, 'gzip'); | |
}); | |
it('should return array with gzipped values when no error occurs', async () => { | |
const stream = new ObjectReadableMock(['value1', 'value2', 'value3']); | |
gzip.callsFake(((info, callback: zlib.CompressCallback) => { | |
callback(null, `gzipped ${info}` as any); | |
})); | |
const result = await notSoSimpleStreamExample(stream as any); | |
expect(zlib.gzip).to.have.been.calledThrice | |
.calledWithExactly('value1', match.func) | |
.calledWithExactly('value2', match.func) | |
.calledWithExactly('value3', match.func); | |
expect(result).to.be.eql([ | |
'gzipped value1', | |
'gzipped value2', | |
'gzipped value3', | |
]); | |
}); | |
it('should throw error when an error on gzip occurs', async () => { | |
const stream = new ObjectReadableMock(['value1', 'value2', 'value3']); | |
const myError = new Error('Some nasty error'); | |
gzip.throws(myError); | |
let thrownError: any; | |
try { | |
await notSoSimpleStreamExample(stream as any); | |
} catch (error) { | |
thrownError = error; | |
} | |
expect(zlib.gzip).to.have.been.calledThrice | |
.calledWithExactly('value1', match.func) | |
.calledWithExactly('value2', match.func) | |
.calledWithExactly('value3', match.func); | |
expect(thrownError).to.be.eq(myError); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment