The FormData object appears to be blank, even though it was supposed to be populated when attempting to send a PDF file using a multipart FormData POST request in Cypress

I am attempting to send a PDF file as a POST request.

The API supports the use of @RequestPart and @RequestParam:

@RequestPart("file") MultipartFile file;
@RequestParam(value = "document-types", required = false) Set<String> documentTypes;

My approach was as follows:

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)
        });
    });
});

However, when I execute this code, I receive:

Status: 400 - Bad Request

Upon inspecting the request in Cypress, I noticed that the body is empty: Body: {}

https://i.sstatic.net/LjZC3.png

While debugging the code, I observed that the data being sent is empty, as shown in the attached screenshot:

https://i.sstatic.net/MbTgl.png

I am puzzled as I have used the following steps to set the data on lines 154 and 155 in the screenshot above:

data.set('file', file);
data.set('document-types', 'New Type');

What am I overlooking here?

Cypress version: 9.0.0

Answer №1

In order to add formData, use the following code snippet as a reference:

    const formData = new FormData()
    formData.append('document', documents[0])
    formData.append('title', documents[0].title)

Answer №3

As mentioned by @Christopher in the response, the variable data was not empty. To view its content, I had to utilize either data.entries() or simply data.get().

However, my attempts to get the code functioning were unsuccessful.

Ultimately, I adopted the method demonstrated in this YouTube video, which proved to be successful.

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);
            })
    });
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

retrieve the value of a specific key from an array

How can I extract key-value pairs from an array in JavaScript where the data is structured like this? jsonData = [ {"dimensions":[5.9,3.9,4.4,3.1,4.8],"icon":0,"curves": [false,false,false,false,false],"id":"p1","color":"0x000000"}, {"dimensio ...

Creating an interactive bootstrap modal: a step-by-step guide

For instance, I have 3 different tags with unique target-data for each one. <a class="btn btn-outline-primary btn-sm" href="#" data-toggle="modal" data-target="#firstdata"> DATA 1 </a> <a class=&q ...

Set the camera to view the world from a y-coordinate of 0 and descend

How can I make the top of the render area in Three.js point to y=0 in the world? I also want the camera to look straight (lookAt) These are my current values: camera = PerspectiveCamera camera.position.z = 1895.8448868133867 camera.fov = 20 screen.width ...

Angular 2 does not update the variable value within a dataservice call on the page until you navigate away from the page and then come back to it

Currently, I am working with Angular2 and have encountered a strange issue. I have a variable that I display on the page, and when a button is clicked, a data service is called to update the value of this variable. Surprisingly, even after changing the val ...

Dynamically setting properties in a Vue component using Angular

After browsing through this interesting discussion, I decided to create a web component: <my-vue-web-comp [userId]="1"></my-vue-web-comp> Initially, everything was working smoothly in Angular when I assigned a static property. Howeve ...

Guide to making a Typescript type guard for a ReactElement type

I'm currently working with three TypeScript type guards: const verifyTeaserOne = (teaser: Teaser): teaser is TeaserOneType => typeof teaser === 'object' && teaser.type.includes('One'); const validateTeaserTwo = ( ...

Encountering an issue with Google distance matrix where property 'text' is undefined

Below is a snippet of code that calculates the distance between two user-provided addresses. This code currently runs when the user submits a form in this manner: $("#distance_form").submit(function (e) { e.preventDefault(); calculateDistance(); }); ...

Is it possible to create a combined header/declaration file in Golang within a single file?

My goal is to automatically generate Golang declaration files based on .json data. While with TypeScript I can consolidate types/declarations in one file using namespaces, it seems more complex to achieve the same with Golang packages and namespacing. In ...

Tips on including variables within quotation marks in JavaScript

I'm currently working on a JavaScript project using Pug. My goal is to use Express and MongoDB to develop a CRUD application that generates an edit button for each post, triggering a specific event when clicked. However, instead of the desired resul ...

React - Anticipated an assignment or invocation of a function

Recently starting my journey with reactjs and encountered a small issue. A pesky error keeps popping up saying: Expect an assignment or function call. It's related to the User function, however, I do call that function when creating a new object. Any ...

Using React.js to create a modal that includes ExpansionPanelDetails with a Checkbox feature

I am trying to achieve a specific visual effect with my code. Here is an example of the effect I want: https://i.stack.imgur.com/cJIxS.png However, the result I currently get looks like this: https://i.stack.imgur.com/547ND.png In the image provided, y ...

What is the best way to adjust my content to be mobile-friendly with the Material UI drawer?

I am facing an issue with adjusting the content in Form.jsx based on the movement of the drawer. When I expand the Drawer by clicking on the menu icon, the content inside the body does not move along with it. How can I make sure that the content moves acco ...

What is the best way to access and interpret a JSON file within an Angular application?

I am facing difficulties while trying to load a JSON file from my local disk in order to populate a FabricJS canvas with the data. Currently, I am encountering issues retrieving the data from the file. Here is what I have attempted so far. app.html < ...

How do I prevent my image slider from scrolling to the top of the page when I click next or prev?

<script> export default { name: "ImageSlider", data() { return { images: [ "https://cdn.pixabay.com/photo/2015/12/12/15/24/amsterdam-1089646_1280.jpg", "https://cdn.pixabay.com/photo/2016/02/17/2 ...

Tips for overcoming indentation issues using ESLint?

Ever since I started using Vue 3 with ESlint, I've been encountering a new problem. Whenever I try to run my code, I am bombarded with numerous errors like: --fix option.</p> I'm looking for ways to disable this troublesome feature of ESl ...

Retrieve information from deeply nested JSON and showcase using Vue-Multiselect

My goal is to fetch data from the server and present it in Multiselect using nested JSON, which can be done through Vue-Multiselect. Once displayed, I should have the ability to add new tags as needed, essentially updating the data. While I can display o ...

In order to ensure accuracy, the 'to' date must always be after the '

By default, when selecting a start date, the end date should be displayed as greater than the start date. However, in my current code, if I select the start date, the end date is set to be the same as the start date. Below is my code snippet. Thank you in ...

How can I utilize the replace function in Angular to swap out a character?

I am attempting to change the characters { and } in an HTML string to {{ and }}. However, when using the replace function, I encounter the following error: $scope.selectedtemplate.template.replace is not a function Below is my code: $scope.selectedte ...

The Katura video is loading properly, yet it is rotating instead of playing

I am working on a web application that involves playing videos from Kaltura platform and then loading the link on an iOS webview. <html> <body> <div id="myEmbedTarget" style="width:400px;height:330px;"></div> ...

HTML5 video player with secondary playlist

Looking for a videoplayer setup where there are two playlists, but only one can play at a time. When choosing a video from the first list initially, nothing happens. However, after selecting a video from the second list, the first list starts working. HTM ...