Mock a multipart/form-data Express.JS request object
Asked Answered
D

2

11

I would like to unit test an Express middleware function which, in turn, uses node-formidable to process a multipart file upload.

Here’s a contrived example:

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}));
    });
}

This code works for me when tested with Chrome and a running Express app.

I want my test code to look like the following where I am mocking the request object, but I can't figure out how to mock the request object with the form data. The formidable callback is not firing:

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);
});

I’ve tried using the form-data library to create a FormData object and pipe it to the request, but no luck, I’m not sure if I’m on the right track or way off. Something like this:

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);
Decapitate answered 4/9, 2016 at 18:30 Comment(2)
Same issue here, I am trying to mock a request which which contains form data.Deuteranopia
I also had a problem with this approach, but I found that I was missing the HTTP POST method when creating the mock request. Once that was addressed it worked as a charmSarcasm
F
5

You could use some request tester like supertest, to do it. Here is an example, assuming that your main file is named 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);
      })

})

Formic answered 20/9, 2018 at 22:54 Comment(1)
Good suggestion for unit testing Http endpoints. Supertest is really easy to use. It maybe useful to say that this also supports the async/await syntaxSarcasm
S
4

Use combination of form-data and mock-express-request. This has worked for me:

const fs = require('fs');
const MockExpressRequest = require('mock-express-request');
const FormData = require('form-data');

const form = new FormData();
form.append('my_file',
  fs.createReadStream(path.join(__dirname, 'fixtures', 'file-upload-test.txt'))
);
const request = new MockExpressRequest({
  method: 'POST',
  host: 'localhost',
  url: '/upload',
  headers: form.getHeaders()
});

form.pipe(request);
doUpload(request, response, next);
Semipalatinsk answered 9/8, 2019 at 2:37 Comment(1)
Great suggestion, it's a really useful way to test utility functions that use an Http request either from standard lib or from express avoiding the need to make Http callsSarcasm

© 2022 - 2024 — McMap. All rights reserved.