How to unit test file upload with Supertest -and- send a token?

Christina Mitchell picture Christina Mitchell · Jul 15, 2016 · Viewed 9.6k times · Source

How can I test a file upload with a token being sent? I'm getting back "0" instead of a confirmation of upload.

This is a failed test:

var chai = require('chai');
var expect = chai.expect;
var config = require("../config");  // contains call to supertest and token info

  describe('Upload Endpoint', function (){

    it('Attach photos - should return 200 response & accepted text', function (done){
        this.timeout(15000);
        setTimeout(done, 15000);
        config.api.post('/customer/upload')
              .set('Accept', 'application.json')
              .send({"token": config.token})
              .field('vehicle_vin', "randomVIN")
              .attach('file', '/Users/moi/Desktop/unit_test_extravaganza/hardwork.jpg')

              .end(function(err, res) {
                   expect(res.body.ok).to.equal(true);
                   expect(res.body.result[0].web_link).to.exist;
               done();
           });
    });
});

This is a Working test:

describe('Upload Endpoint - FL token ', function (){
   this.timeout(15000);
    it('Press Send w/out attaching photos returns error message', function (done){
    config.api.post('/customer/upload')
      .set('Accept', 'application.json')
      .send({"token": config.token })
      .expect(200)
      .end(function(err, res) {
         expect(res.body.ok).to.equal(false);
         done();
    });
});

Any suggestions are appreciated!

Answer

Derek Hill picture Derek Hill · Mar 16, 2020

With supertest 4.0.2 I was able to set the token and attach the file:

import * as request from 'supertest';

return request(server)
  .post('/route')
  .set('Authorization', 'bearer ' + token)
  .attach('name', 'file/path/name.txt');

And even better, per the docs, you can make a Buffer object to attach:

const buffer = Buffer.from('some data');

return request(server)
  .post('/route')
  .set('Authorization', 'bearer ' + token)
  .attach('name', buffer, 'custom_file_name.txt');