Skip to content

Instantly share code, notes, and snippets.

@fabiob
Created September 10, 2017 02:20
Show Gist options
  • Save fabiob/70b6d7d3022dc6fa36b01ce1d60a5de4 to your computer and use it in GitHub Desktop.
Save fabiob/70b6d7d3022dc6fa36b01ce1d60a5de4 to your computer and use it in GitHub Desktop.
Testing binary downloads using chai-http
import 'mocha';
import { expect, request } from 'chai';
import chaiHttp = require('chai-http');
import { app } from '../../server';
chai.use(chaiHttp);
const BIN_FILE = new Buffer([
0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
]);
describe('binary download should work', () => {
let r : ChaiHttp.Response;
before(async() => {
r = await request(app)
.get(`/download`)
.buffer().parse(binaryParser);
});
it('should return HTTP 200: OK', () => {
expect(r.status).to.equal(200);
});
it('should return the binary data correctly', () => {
expect(r.body).to.deep.equal(BIN_FILE);
});
});
// Source: https://stackoverflow.com/a/14802413/292586
function binaryParser(res : any, cb : (e? : Error, r? : any) => void) {
let data = '';
res.setEncoding('binary');
res.on('data', function(chunk : any) { data += chunk; });
res.on('end', function() { cb(undefined, new Buffer(data, 'binary')); });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment