2

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
ArrchanaMohan
  • 2,314
  • 4
  • 36
  • 84

1 Answers1

1

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
})
Alapan Das
  • 17,144
  • 3
  • 29
  • 52
  • Nope. Still it return 400 bad request. do I need to add any param in the header part to parse the text request in cypress – ArrchanaMohan Nov 02 '21 at 06:43
  • So if you are passing parameters in your URL, you have to use `qs`. I have updated the answer, you can check. – Alapan Das Nov 02 '21 at 06:52