node.js 如何在 mocha 中使用文件上传进行单元测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10120866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to unit test with a file upload in mocha
提问by Mark Gia Bao Nguyen
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?
我有一个基于 Express.js 的应用程序,我想测试文件上传功能。我正在尝试重现解析为 req.files 的对象(使用 express.bodyParser 中间件时)。我怎样才能做到这一点?
采纳答案by Jesper
You can do this directly in Mocha but it's a bit tricky. Here's an example posting an image:
您可以直接在 Mocha 中执行此操作,但这有点棘手。这是发布图像的示例:
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 nameparameter 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]
Content-Disposition的name参数是您的文件将可以通过 req.files 访问的内容(所以在我的示例中为 req.files.image)您还可以使用这样的数组值:name="images[]" 和您的文件(s) 将通过数组提供,例如: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
另外,如果您还没有使用它,您应该看看这个(使 mocha/express 测试更容易~位~):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.jsOr simply move over to supertest..
编辑:由于 express 3-beta5,express 使用 supertest。要查看旧的 http.js 代码,请看这里:https: //github.com/visionmedia/express/blob/3.0.0beta4/test/support/http.js或者简单地移至 supertest ..
回答by Hyman
Here is an example of how you would do it with supertestmodule.
这是一个如何使用supertest模块执行此操作的示例。
var should = require('should'),
supertest = require('supertest');
var request = supertest('localhost:3000');
describe('upload', function() {
it('a file', function(done) {
request.post('/your/endpoint')
.field('extra_info', '{"in":"case you want to send json along with your file"}')
.attach('image', 'path/to/file.jpg')
.end(function(err, res) {
res.should.have.status(200); // 'success' status
done();
});
});
});
回答by Monica
var expect = require('expect.js');
supertest = require('supertest');
var request = supertest('localhost:3000');
describe('create album', function () {
it('valid ', function (done) {
request.post('/albums')
.set('Authorization', 'Token eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.IjkxMTg3NTk1ODg2MCI.gq32xfcOhv5AiZXJup5al1DGG0piyGWnrjZ5NouauCU')
.field('Content-Type', 'multipart/form-data')
.field('name', 'moni')
.field('description', 'Nature+Pics')
.field('caption', 'nature')
.field('contacts', '["' + 911354971564 + '","' + 919092888819 + '"]')
.field('dimensions', '{"photo1":{"height": 10, "width": 10}, "photo2":{"height": 20, "width": 20}, "photo3":{"height": 20, "width": 20}, "photo4":{"height": 20, "width": 20}, "photo5":{"height": 20, "width": 20}}')
.attach('photo1', '/home/monica/Desktop/pic/1.jpeg')
.attach('photo2', '/home/monica/Desktop/pic/2.jpeg')
.attach('photo3', '/home/monica/Desktop/pic/3.jpeg')
.attach('photo4', '/home/monica/Desktop/pic/4.jpeg')
.attach('photo5', '/home/monica/Desktop/pic/5.jpeg')
.end(function (err, res) {
if (err) {
console.log(err);
} else expect(res.status).to.equal(200);
done();
});
});
});
回答by Jun Wang
Changing attach('image') to attach('file') will solve the problem of req.files.file not defined.
将 attach('image') 改为 attach('file') 将解决 req.files.file 未定义的问题。
var should = require('should'),
supertest = require('supertest');
var request = supertest('localhost:3000');
describe('upload', function() {
it('a file', function(done) {
request.post('/your/endpoint')
.field({field1: 'xxx', field2: 'yyy'})
.attach('file', 'path/to/file.jpg')
.end(function(err, res) {
res.should.have.status(200) // 'success' status
done()
});
});
});
回答by Mark Gia Bao Nguyen
Just came across this module by TJ: https://github.com/visionmedia/supertest.
刚刚通过 TJ 遇到了这个模块:https: //github.com/visionmedia/supertest。
回答by drinchev
You might try using zombie.js https://github.com/assaf/zombie, it creates a virtual browser for testing with basic functionality. It can attach a file to a specific input field and supports cookies and sessions
您可以尝试使用zombie.js https://github.com/assaf/zombie,它会创建一个虚拟浏览器来测试基本功能。它可以将文件附加到特定的输入字段并支持 cookie 和会话
related gist : https://gist.github.com/764536
回答by Jerry
If using request promiseyou can simply do this, sending formData is built into it:
如果使用请求承诺,您可以简单地执行此操作,发送 formData 内置于其中:
var options = {
method: 'POST',
uri: base + '/api/image/upload',
formData: {
someField: 'someValue',
anotherField: 'anotherValue',
file: {
// path to image
value: fs.createReadStream('./testImg.png'),
options: {
filename: 'testImg.png',
contentType: 'image/png'
}
}
}
};
let resp;
try {
resp = await request.post(options);
body = JSON.parse(resp);
} catch (e) {
console.log(e);
resp = e.response;
code = resp.statusCode;
body = JSON.parse(resp.body);
}
// access what is returned here, check what needs to be
assert.equal(code, 200, 'Status: ' + code + ': ' + body.error);
assert.equal(body.success, true);
assert.exists(body.image);

