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

标签 node.js unit-testing express jasmine formidable

我想对 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, res, 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, res, 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);
      })

})

关于node.js - 模拟一个 multipart/form-data Express.JS 请求对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39320201/

相关文章:

javascript - 尝试从 NodeJS 后端的 API 获取数据时出现请求过多错误,但适用于 React 前端

node.js - 使用 Express.js 设置持久性 cookie

c# - 在 Microsoft 测试项目中包含资源 dll

typescript - 如何在 React Native 中使用 TypeScript 模拟 React Navigation 的导航 Prop 以进行单元测试?

c# - 如何为没有输入和输出的方法编写单元测试?

node.js - 如何在Sequelize ORM中获取没有前缀表名的连接数据结果

javascript - 在 NodeJS api 服务器中从客户端获取 JSON 内容

javascript - Express.js CRUD 应用程序错误 : update function does wrong redirect

node.js - 批量写入 - 类型错误 : Cannot create property '$set' on number '0' at applyTimestampsToUpdate - mongoose or mongodb

mysql - 服务器 webRTC 连接的好方法