Skip to content

Instantly share code, notes, and snippets.

@yoitsro
Last active August 29, 2015 14:02
Show Gist options
  • Save yoitsro/d62b15df5f6de843e1e8 to your computer and use it in GitHub Desktop.
Save yoitsro/d62b15df5f6de843e1e8 to your computer and use it in GitHub Desktop.
Hapi server injection with multipart form
it('creates a new collection with an image as a binary buffer', function(done) {
var endpoint = '/collections';
var url = SERVER_URL + endpoint;
var method = 'POST';
var form = new FormData();
form.append('json', {"name": "Red stuff collection","filter": {"colour": "red"}});
form.append('image', require('fs').readFileSync('./test/data/image.jpg'));
var endpoint = '/collections';
var url = SERVER_URL + endpoint;
var method = 'POST';
server.inject({url: url, method: method, payload: form }, function(res) {
console.log(res.result);
expect(res.statusCode).to.equal(201);
done();
});
};
@yoitsro
Copy link
Author

yoitsro commented Jun 16, 2014

No public project, but this is the block of code I've been trying to work with before trying your solution. I tried your solution, but couldn't figure out how it should all link together. This is for an integration test.

@bendrucker
Copy link

form is a stream, even if it's just composed of buffers as above. You need to read out its data into an actual buffer before it can be written as a payload. Using stream-to-promise:

streamToPromise(form).then(function (form) {
  server.inject({url: url, method: method, payload: form}, function (res) {
    expect(res.statusCode).to.equal(201);
    done();
  });
});

@yoitsro
Copy link
Author

yoitsro commented Jun 16, 2014

Thanks Ben! I'm now getting a TypeError: Object #<Object> has no method 'on' error in FormData.CombinedStream.append (/Users/ro/Documents/sampleProject/node_modules/form-data/node_modules/combined-stream/lib/combined_stream.js:43:14)

This is being thrown from line 8.

@bendrucker
Copy link

Try bringing in the image as a readable stream instead of a buffer. Otherwise this is identical to the way I've successfully implemented it in the past.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment