Search code examples
automationcypresscypress-component-test-runner

How to handle the plain/text POST request in the cypress


I have a postman collection and It's POST call and the request body is type of plain/text and I just want to automate this using cy.request but I'm not sure how to pass the test body in the cy.request body section and it returned 400 bad request if I run the below code.

 cy.request({
        url: `${url}/user`,
        method: "POST",
   headers: {
            'Content-Type': 'plain/text'
        },
        body: {
            "confirmEmail": "true"
        }
    }).then(res =>{
        cy.task('log',"Email id "+res.body.emailAddress);
        return res.body;
    });
}

The above request return .json response but the input request if text format and the same working fine in the postman tool.

Passing the request body in the below format in the postman tool and its working fine.

confirmEmail=true

Solution

  • My assumption is in the request body our endpoint is expecting a boolean value, but you are passing a string. So changing "confirmEmail": "true" to "confirmEmail": true should work.

    cy.request({
      url: `${url}/user`,
      method: 'POST',
      headers: {
        'Content-Type': 'plain/text',
      },
      body: {
        confirmEmail: true,
      },
    }).then((res) => {
      cy.log(res.body.emailAddress) //prints email address from response body
    })
    

    In case you need to pass parameters in your URL you can directly use qs

    cy.request({
      url: `${url}/user`,
      method: 'POST',
      qs: {
        confirmEmail: true,
      },
      headers: {
        'Content-Type': 'plain/text',
      },
    }).then((res) => {
      cy.log(res.body.emailAddress) //prints email address from response body
    })