如何使用mocha中的文件上传进行单元测试 [英] How to unit test with a file upload in mocha
问题描述
我有一个基于Express.js的应用程序,我想测试文件上传功能。我正在尝试重现被解析为req.files的对象(使用express.bodyParser中间件时)。我该怎么做?
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 middleware). How can I do this?
推荐答案
你可以直接在摩卡车上做,但这有点棘手。以下是一个发布图片的示例:
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()
})
Content-Disposition的名称参数是您的文件可以通过req.files访问(所以req.files。图像为我的例子)
您还可以使用像这样的数组值:name =images []和您的文件wil我可以通过一个数组,例如:req.files.images [0]
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]
如果你还没有使用它,你应该看看这个摩卡/快递测试〜〜位〜更容易):
https://github.com/visionmedia/express/blob/master/test/support/http.js
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
修改 :由于Express 3-beta5,表达使用最高。要查看旧的http.js代码,请看这里: https ://github.com/visionmedia/express/blob/3.0.0beta4/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..
这篇关于如何使用mocha中的文件上传进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!