Home > front end >  FormData object is empty even though it is being set when trying to send a pdf file as a multipart F
FormData object is empty even though it is being set when trying to send a pdf file as a multipart F

Time:11-17

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: {}

enter image description here

When I tried to debug the code, I see that data is being sent empty as you see on the attached screenshot:

enter image description here

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

CodePudding user response:

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:

CodePudding user response:

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)
  • Related