learnTrack / Q-A

Questions and Answers
10 stars 0 forks source link

Testing file uploads in hapijs #70

Open heron2014 opened 8 years ago

heron2014 commented 8 years ago

https://github.com/hapijs/hapi/issues/1543 https://gist.github.com/Couto/127ca8a6bd28ecc4a084 https://www.npmjs.com/package/form-data

full example WIP

heron2014 commented 8 years ago

Example of how to test upload file to the Google Drive

var Code = require('code');
var Lab = require('lab');
var Server = require('../lib/index.js');

var lab = exports.lab = Lab.script();
var describe = lab.experiment;
var expect = Code.expect;
var it = lab.test;

var FormData = require('form-data');
var fs = require('fs');
var streamToPromise = require('stream-to-promise');
describe('/file/upload file, function () {

  it('Upload file', function (done) {

    //mock the upload of the file
    var nock = require('nock');
    nock('https://www.googleapis.com')
      .post('/upload/drive/v3/files?uploadType=multipart')
      .reply(200, {id: 'theIdOfTheFile'}); //in our example we reply the id from google drive

      var form = new FormData();
      form.append('id', '123'); // your form data
      form.append('selectedFile', fs.createReadStream('./test/fixtures/file.txt'));

    streamToPromise(form).then(function (payload) {
      Server.init(0, function (err, server) {

        expect(err).to.not.exist();

        var options = {
          method: "POST",
          url: "/file/upload",
          headers: form.getHeaders(),
          payload: payload,
          credentials: { id: "12", "name": "Some name", valid: true}
        };

        server.inject(options, function (res) {
          //redirect to the candidate page
          expect(res.statusCode).to.equal(302);
          expect(res.headers.location).to.equal('/candidate/123');
          server.stop(done);
        });
      });

    })

  });
});