I want to send the pdf file as a POST request.
The API accepts @RequestPart and @RequestParam:
@RequestPart("file") MultipartFile file;
@RequestParam(value = "document-types", required = false) Set<String> documentTypes;
I tried to do it that way:
it('test', () => {
cy.fixture(pdfFilePath, "binary").then(file => {
const data = new FormData();
data.set('file', file);
data.set('document-types', 'New Type');
cy.request({
method: "POST",
url: '/api/v4/documents',
headers: {
accepts: "multipart/form-data",
authorization: authString
},
body: data
}).then((response) => {
expect(response.status).to.eq(200)
});
});
});
And when I run this I get:
Status: 400 - Bad Request
In Cypress I see that body in request sent is empty:
Body: {}
When I tried to debug the code, I see that data is being sent empty as you see on the attached screenshot:
And I wonder why because I try to set the data by doing these steps in lines 154 and 155 on the above screenshot:
data.set('file', file);
data.set('document-types', 'New Type');
What am I missing here?
Cypress version: 9.0.0
you have to append formData, code below is just an example:
const formData = new FormData()
formData.append('file', files[0])
formData.append('name', files[0].name)
It's not empty, you have to make use of data.entries() to view the content.
It seems like the cy.request() function tries to convert the FormData Object to a JSON object which is wrong.
From the documentation of cypress you should also make also use of the form: true setting.
References:
As @Christopher mentioned in the answer,data was not empty. I had to use data.entries() or simply data.get() to view the content.
But anyways I was not able to make that code working.
Instead, I followed the approach presented in this youtube video and it worked.
it.only('test', () => {
function form_request(method, url, formData, done) {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader(
"Authorization",
"Basic YWRtaW46YWRtaW4="
);
xhr.onload = function () {
done(xhr);
};
xhr.onerror = function () {
done(xhr);
};
xhr.send(formData);
}
const fileName = "PdfFileName.pdf";
const method = "POST";
const url = '/api/v4/documents';
const fileType = "application/pdf"
cy.fixture(pdfFilePath, "binary")
.then((txtBin) => Cypress.Blob.binaryStringToBlob(txtBin))
.then((blob) => {
const formData = new FormData();
formData.append("file", blob, fileName);
formData.append("document-types", "New Type");
form_request(method, url, formData, function (response) {
expect(response.status).to.eq(200);
})
});
})