I'm using the stream-to-promise npm module to create the multipart/form-data payload in my jasmine test. My payload includes an image file as a buffer but when the payload is put through stream-to-promise it changes or corrupts my original image buffer in the payload somehow and so my tests are failing. Is there a way to prevent this?
it('test /identity-verification/your-first-form-of-id POST with validation passing', function(done){
var form = new FormData();
var image = fs.createReadStream("image.png");
streamToBuffer(image, function (err, buffer) {
form.append('firstID', 'passport');
form.append('firstIDImage', buffer);
var headers = form.getHeaders();
streamToPromise(form).then(function(payload) {
var options = {
method: 'POST',
url: '/identity-verification/your-first-form-of-id',
payload: payload,
headers: headers
};
server.inject(options, function(response) {
expect(response.statusCode).toBe(302);
expect(response.headers.location).toMatch('/identity-verification/your-first-form-of-id/upload-successful');
done();
});
});
});
});
The buffer in the payload after being put through stream-to-promise looks like this:
You don't need stream-to-buffer. You've already got the buffer from createReadStream. If you get rid of that, it should work. One thing to be careful of is that your maxBytes is set high enough to accomodate your test image. This was causing some cryptic errors when I was testing.
The code below is working fine for me.
var streamToPromise = require("stream-to-promise");
var FormData = require("form-data");
var fileTypeModule = require("file-type");
var fs = require("fs");
var q = require("q");
var Hapi = require('hapi');
var server = new Hapi.Server({ debug: { request: ['error'] } });
server.connection({
host: 'localhost',
port: 8000
});
server.route({
method: 'POST',
path: '/test',
handler: function(request, reply) {
var data = request.payload.firstIDImage;
var fileType = fileTypeModule(data);
reply(fileType);
},
config: {
payload: { maxBytes: 1048576 }
}
});
var start = server.start();
var form = new FormData();
var headers = form.getHeaders();
form.append('firstID', 'passport');
form.append('firstIDImage', fs.createReadStream("image.png"));
var append = streamToPromise(form);
q.all([start, append]).then((results) => {
var options = {
method: 'POST',
url: '/test',
payload: results[1],
headers: headers
};
server.inject(options, function(response) {
console.log(response.payload);
});
});