node.js – 模拟multipart / form-data Express.JS请求对象

我想对Express中间件功能进行单元测试,然后使用 node-formidable来处理多部分文件上传.

这是一个人为的例子:

function doUpload(req,res,next) {
    const form = new formidable.IncomingForm();
    form.uploadDir = this.mediaDir;
    form.keepExtensions = true;
    form.type = 'multipart';
    form.multiples = true;

    form.parse(req,function(err,fields,files) {
        res.writeHead(200,{'content-type': 'text/plain'});
        res.write('received upload:\n\n');
        res.end(util.inspect({fields: fields,files: files}));
    });
}

在使用Chrome和正在运行的Express应用程序进行测试后,此代码适用于我.

我希望我的测试代码看起来像我在模拟请求对象,但我无法弄清楚如何使用表单数据模拟请求对象.强大的回调没有触发:

it(‘handles uploads’,(done) => {
    const mockReq = http.request({
        host: 'example.org',});
    mockReq.url = ‘/upload’;

    const res = jasmine.createSpyObj('response',[ 'json','send','status','render','header',‘redirect’,‘end’,‘write;]);
    const next = jasmine.createSpy('next');

    //*how to emulate a request with a multipart file upload)

    doUpload(req,next);
    res.write.and.callFake(done);
});

我已经尝试使用form-data库创建一个FormData对象并将其传递给请求,但没有运气,我不确定我是否在正确的轨道上或离开.像这样的东西:

var form = new FormData();

const buff = fs.readFileSync(path.join(__dirname,'../fixtures/logo.png'));

form.append('file',buff,{
    filename: 'logo.jpg',contentType: 'image/png',kNownLength: buff.length
});
form.append('name','logo');

req.headers = form.getHeaders();

form.pipe(req);
doUpload(req,next);

解决方法

您可以使用像 supertest这样的请求测试程序来执行此操作.这是一个示例,假设您的主文件名为app.js:

const request = require('supertest');
const app = require('app.js');

it('Uploads a file',function(){
    request(app)
      .post('/upload')
      .field('name','logo') //adds a field 'name' and sets its value to 'logo'
      .attach('file','/path/to/file') // attaches the file to the form
      .then(function(response){
          // response from the server
          console.log(response.status);
          console.log(response.body);
      })

})

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...