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!
SuperTest is an HTTP assertions library that allows you to test your Node. js HTTP servers. It is built on top of SuperAgent library, wich is an HTTP client for Node. js.
What Is SuperTest? SuperTest is a Node. js library that helps developers test APIs. It extends another library called superagent, a JavaScript HTTP client for Node.
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');
The official document states
When you use .field() or .attach() you can't use .send() and you must not set Content-Type (the correct type will be set for you).
So replace
.send({"token": config.token})
with
.field("token", config.token)
It seems like the token field is overrided when attaching a file. My workaround is to add token to URL query parameter:
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/?token='+config.token)
.attach('file', '/Users/moi/Desktop/unit_test_extravaganza/hardwork.jpg')
.expect(200)
.end(function(err, res) {
expect(res.body.ok).to.equal(false);
done();
});
});
Your authentication middleware must be set to extract the JWT from URL query parameter. Passport-JWT performs this extraction on my server.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With