I have an app built on Express.js and I\'d like to test the file upload functionality. I\'m trying to reproduce the object parsed to req.files (when using express.bodyParser
You can do this directly in Mocha but it's a bit tricky. Here's an example posting an image:
var filename = 'x.png'
, boundary = Math.random()
request(app)
.post('/g/' + myDraftGallery._id)
.set('Content-Type', 'multipart/form-data; boundary=' + boundary)
.write('--' + boundary + '\r\n')
.write('Content-Disposition: form-data; name="image"; filename="'+filename+'"\r\n')
.write('Content-Type: image/png\r\n')
.write('\r\n')
.write(fs.readFileSync('test/'+filename))
.write('\r\n--' + boundary + '--')
.end(function(res){
res.should.have.status(200)
done()
})
The name parameter of Content-Disposition is what your file will be accessible as via req.files (so req.files.image for my example) You can also use an array value like this: name="images[]" and your file(s) will be available via an array, e.g: req.files.images[0]
Also if you're not already using it you should have a look at this (makes mocha/express testing a ~bit~ easier): https://github.com/visionmedia/express/blob/master/test/support/http.js
Edit: Since express 3-beta5, express uses supertest. To look at the old http.js code look here: https://github.com/visionmedia/express/blob/3.0.0beta4/test/support/http.js Or simply move over to supertest..