Sometimes in your test, you need to make api call with form-data
as payload - upload file for example, it’s not a hard task that you can achieve easily with REST helper. Okay, what do you need to do so?
First you need to install this package, a library to create readable "multipart/form-data"
streams. Can be used to submit forms and file uploads to other web applications.
npm i form-data --save
Now the test file looks something like this, don’t worry, I’m gonna go through and explain you what it means:
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');
Scenario('I can upload file successfully ', async () => {
let form = new FormData();
form.append('a', JSON.stringify([value]));
form.append('b', 'valuer')
form.append('c', JSON.stringify({ "key": "Automation Tests" }));
form.append('file', fs.createReadStream(path.join(__dirname, '/fixtures/test.jpg')));
let res = await I.sendPostRequest(yourEndpoint, form, { Authorization: token, ...form.getHeaders() });
expect(res.status).to.eq(200);
});
All right, let’s deep into the lines and learn what they are:
const FormData = require('form-data');
-> this to require the form-data
lib.
const fs = require('fs');
-> this to create the read stream of file you want to upload.
const path = require('path');
-> this to handle the path to your file you want to upload.
let form = new FormData();
-> initialize a new form.
form.append('a', JSON.stringify([value]));
-> append a
field with value is an array, you need to stringify the value if it is other than text string.
form.append('b', 'valuer')
-> append b
field with value is a text string.
form.append('c', JSON.stringify({ "key": "Automation Tests" }));
-> append b
field with value is an object, yes, you’re right, we need to stringify the value if it is other than text string.
Now comes the interesting part, appending the file
field with value is a file stream.
form.append('file', fs.createReadStream(path.join(__dirname, '/fixtures/test.jpg')));
let res = await I.sendPostRequest(yourEndpoint, form, { Authorization: token, ...form.getHeaders() });
Now let’s try to make a post call with payload is a form data. Awesome! You made it!
Note: { Authorization: token, ...form.getHeaders() }
you should always use the headers from form, if you need to append your headers with something else, that’s the way.
Enjoy the API call with form-data
.