I'm trying to save my request's body as a variable on cypress, so I can use the same body for another request. How can I do it?
The code below is working, but I need to save BODY as a variable for another request. Is there a easy way to do it?
cy.request({
url: "/api/affiliate/create",
method: "POST",
headers:
{
Authorization: `bearer ${access_token}`,
},
body: {
"address": Random.address,
"address_complement": Random.address_complement,
"address_city": Random.address_city,
"address_number": `${Random.address_number}`,
"address_district": Random.address_district,
"address_state": Random.address_state,
"cep": `${Random.cep}`,
"cnpj": Random.cnpj,
"company_name": Random.company_name,
"headquarters": fAffiliate.headquarters[1],
"ie": `${Random.ie}`,
"phone": Random.phone,
"rntrc": `${Random.rntrc}`,
"status": fAffiliate.status[0],
"trading_name": Random.trading_name
}
Put it in a variable first, then use the variable in the Cypress call.
const body = {
"address": Random.address,
"address_complement": Random.address_complement,
"address_city": Random.address_city,
"address_number": `${Random.address_number}`,
"address_district": Random.address_district,
"address_state": Random.address_state,
"cep": `${Random.cep}`,
"cnpj": Random.cnpj,
"company_name": Random.company_name,
"headquarters": fAffiliate.headquarters[1],
"ie": `${Random.ie}`,
"phone": Random.phone,
"rntrc": `${Random.rntrc}`,
"status": fAffiliate.status[0],
"trading_name": Random.trading_name
};
cy.request({
url: "/api/affiliate/create",
method: "POST",
headers: {
Authorization: `bearer ${access_token}`,
},
body: body
})
Then you can use the body variable again for a second request.
You may also wish to save it as a fixture, to use in more than one spec.
In /support/index.js
const body = {...}
cy.writeFile('cypress/fixtures/request-body.json', body)
In the test
cy.fixture('request-body.json').then(body => {
cy.request({
url: "/api/affiliate/create",
method: "POST",
headers: {
Authorization: `bearer ${access_token}`,
},
body
})
})