Testing a binary file upload with mocha

I am currently working on a small API with nodejs and am fixing what requires a file upload, getting a binary string.

What I don't know how to do is test it with mocha, so I did a search and found it on a stack overflow Unit test uploading a file with mocha , its a great start, but it won't work because its a multipart form submit and what I require the client to post to the api is a file as a stream.

Here is my controller:

exports.uploadVideo = function(req, res, next) {
    var video = "public/video/" + req.params.videoId + ".mp4",
        util  = require('util'),
        exec = require('child_process').exec;

    var newFile = fs.createWriteStream("./uploads/" + video);

    req.pipe(newFile);

    req.on('end', function () {
        var cmd = 'qtfaststart ' + './uploads/' + video;
        var qtfaststart = exec(cmd, function(error, stdout, stderr){
            if (error === "atom not found, is this a valid MOV/MP4 file?\n" || error !== null) {
                return next(new restify.ConflictError("Error: " + stdout));
            } else {
                fs.chmodSync('./uploads/' + video, '644');
                Video.findOne( { _id: req.params.videoId }, function(err, video) {
                    if (err) return next(new restify.ConflictError(err));
                    if (!video) {
                        newVideo = new Video({
                            _id: req.params.videoId,
                            file: video});
                        newVideo.save()

                    } else {
                        video.file = video;
                        video.increment();
                        video.save();
                    }
                });
            }
        });
    });

    req.on('error', function(err){
        return next(new restify.NetworkConnectTimeoutError(err));
    });
};

      

So, given this controller that receives the stream (binary) and puts the stream together on the server, how would I test this controller with mocha?

+2


source to share


2 answers


You can simply use http

for this:



it('should be possible to upload a file', function(done) {
  var http        = require('http');
  var options     = require('url').parse(YOUR_URL);
  options.method  = 'POST';

  var req = http.request(options, function(response) {
    // TODO: check for errors, correct response, etc...
    done(...);
  });

  require('fs').createReadStream(YOUR_TEST_FILE).pipe(req);
});

      

+1


source


You want to use the request module from within mocha. It supports multipart forms.



0


source







All Articles