cypress: POST request using formdata doesn't work

I created the following command in cypress commands.js: -

Cypress.Commands.add("form_request", (method, urlPathParam, formData) => {
  return cy
    .server()
    .route(method, "https://admin.teamapp.myhelpling.com" + urlPathParam)
    .as("formRequest")
    .window()
    .then(win => {
      const xhr = new XMLHttpRequest();
      xhr.open(method, "https://admin.teamapp.myhelpling.com" + urlPathParam);
      xhr.setRequestHeader("accept", "application/json");
      xhr.setRequestHeader("access-token", accesstoken);
      xhr.setRequestHeader("client", client);
      xhr.setRequestHeader("expiry", expiry);
      xhr.setRequestHeader("token-type", tokentype);
      xhr.setRequestHeader("uid", uid);
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xhr.send(formData);
    })
    .wait("@formRequest");
});

Kindly note that I’m reading all header values from previous login request.

In the test spec file I’m doing the following inside a Test case: -

cy.AppLogin();
let dataname = "Test FORMDATA API";
    let formData = new FormData();
    formData.append("client[name]", dataname);
    formData.append(
      "client[client_logo_attributes][content]",
      cy.fixture("/images/clients/Golden JPEG.jpeg")
    );
cy.form_request("POST", "/admin/clients", formData).then(response => {
  cy.log(response.status);
});

On cypress electron app I see the following error: -

CypressError: Timed out retrying: cy.wait() timed out waiting 5000ms for the 1st request to the route: 'formRequest'. No request ever occurred.

Commenting .wait("@formRequest"); out from commands.js code above I get the following error: -

POST https://admin.teamapp.myhelpling.com/admin/clients 405 (Method Not Allowed) 

In the sources tab on dev tool I see a X(cross) mark on xhr.send(formData) line provided below: -

    xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryAGOGnFVPveAa8gfv");
    xhr.send(formData);
  }); //.wait("@formRequest");
});

I’ve no idea what to do here. I’m also new to cypress. Kindly suggest.

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 2
  • Comments: 25 (5 by maintainers)

Most upvoted comments

I wish this was supported in Cypress without having to do workarounds. This is a very common use case.

@Vinod-Gulia @lorennorman Appreciate your feedback for above request plz

@gitsaquib The solution for me was to use “fetch”.

//First, you need to read file, which you wont to upload
cy.readFile(`cypress/fixtures/${fileName}`).then((str) => {
// Create blob, set type of data:
      let blob = new Blob([str], {type: 'text/plain'})
// Create headers:
      const myHeaders = new Headers({
        'Authorization': `Bearer ${Cypress.env('token')}`
      })
// Create FordData
      let formData = new FormData()
      formData.append('hash', hashFile)
      formData.append('file', blob)
// You can specify URL globally in cypress.json:
      fetch(`${Cypress.env('backendURL')}/file`, {
        method: 'PUT',
        headers: myHeaders,
        body: formData,
      }).then((resp) => {
// And wait for response:
        Cypress.env('respStatus', resp.status)
        return Promise.resolve(resp)
      })
        .then((resp) => {
          return resp.json()
        })
        .then((data) => {
        //  some expect
        })
// You set alias and, wait alias in the following tests: 
    }).as('Update txt file').wait(100)

@arthsiddh Are you lazy or is it too difficult to test it by yourself?

You can follow this

https://youtu.be/M7ofat3ZI4s

On Wed, 17 Mar, 2021, 2:15 pm SanjayVeernala, @.***> wrote:

How can I send form data with header multipart/form-data without convert to x-www-form-urlencoded?

const querystring = require(‘querystring’);const options = { ‘method’: ‘POST’, ‘url’: ‘http://localhost:3000/api’, ‘headers’: { ‘Content-Type’: ‘multipart/form-data; Boundary=XXX’, ‘Accept’: ‘application/json’ }, body: querystring.stringify({ login: ‘some’, email: @.***', password: ‘some12345’, CSR: ‘some’ }) } cy.request(options).then((response) => { if (error) throw new Error(error); console.log(response.body); });

@linababenko https://github.com/linababenko try maybe sending body data as querystring.stringify({…}) with no form: true.

Did you get a solution on this? I am facing a similar issue when uploading test images through Jira API

Is this working?

— You are receiving this because you modified the open/close state. Reply to this email directly, view it on GitHub https://github.com/cypress-io/cypress/issues/3468#issuecomment-800905762, or unsubscribe https://github.com/notifications/unsubscribe-auth/AHH7UGR3BP62B3XYKMU2CCDTEBT3JANCNFSM4GXOPNKA .

@Elshaikh, I think you should be able to update the this.bodyjson to just be bodyjson to match the arguments being received to the .then() callback function. Does this work?