Unit Test with Unsupported Media Type response in HapiJS

3

I'm doing the unit-testing with lab for a service in hapijs . The service basically asks for a file:

server.route({
  method: 'POST',
  path: '/file',
  config: {
    payload:{
      output:'stream',
      parse: true,
      allow: 'multipart/form-data'
    }
  },
  handler: function(request, reply){
    reply({ message: 'File saved' });
  }
});

Being your unit-test :

var request = {
  method: 'POST',
  url: '/file',
  payload: {
    file: {
      value: fs.createReadStream('input.csv')
    }
  }
};

lab.test('it return the default message to file index', (done) => {
  server.inject(request, (response) => {
    Code.expect(response.result.message).to.match(/File saved/);
    Code.expect(response.statusCode).to.equal(200);
    done();
  });
});

The fact is that when I run the unit testing returns { statusCode: 415, error: 'Unsupported Media Type' } . So I think I should indicate the content-type in headers but I'm not sure what values are needed and where they should go.

    
asked by learnercys 06.01.2016 в 21:33
source

2 answers

3

After researching I found the answer using form-data and stream-to-promise :

var FormData = require('form-data');
var streamToPromise = require('stream-to-promise');

lab.test('it return the default message to file index', (done) => {
  var form = new FormData();
  form.append('file', fs.createReadStream('input.csv'));

  streamToPromise(form).then((payload) => {
    var request = {
      method: 'POST',
      url: '/file',
      payload: payload,
      headers: form.getHeaders()
    };

    server.inject(request, (response) => {
      Code.expect(response.result.message).to.match(/File saved/);
      Code.expect(response.statusCode).to.equal(200);
      done();
    });
  });
});

Reference: server.inject for multipart / form-data # 1711

    
answered by 07.01.2016 / 21:36
source
0

To add the headers to that request you can modify your request object like this:

var request = {
  method: 'POST',
  url: '/file',
  headers : {
        "Content-Type" : "..."
      },
  payload: {
    file: {
      value: fs.createReadStream('input.csv')
    }
  }
};

You can check the comments in this issue to see a user's example.

    
answered by 06.01.2016 в 23:49