Home > Back-end >  Cypress network request with dynamic body
Cypress network request with dynamic body

Time:03-02

I would like to create cypress custom method which will be using parameter as a dynamic request body (to avoid code duplicate because url, method and headers are always the same) like that:

var bodyValue = 
`abc
 abc
 abc`

 var bodyValue2 = 
`bbb
 bbb
 bbb`

Cypress.Commands.add("myRequest", () => {


  cy.request({

    url: "xxx",
    method: 'PUT',

    headers: {
      authorization: cookies
    },

    body: bodyValue

    
  })

})

it always ends with

The response we got was:

Status: 409 - Conflict
Headers: {
  xxx
  xxx
  xxx
}
Body: {
  "message": "Setting Deleted"
}

Whats funny if I take value from my variable and just paste it into body:

cy.request({

    url: "xxx",
    method: 'PUT',

    headers: {
      authorization: cookies
    },

    body: {
     abc
     abc
     abc
}

})

It is always working

I also have tried

cy.request({

    url: "xxx",
    method: 'PUT',

    headers: {
      authorization: cookies
    },

    body: {bodyValue}

})

It is weird because because body after that is not

     abc
     abc
     abc

but

{"bodyValue":
   abc
   abc
   abc
}

which may be the cause. I don't know how to achieve my goal.

My acutal bodyValue:

{
    "revision": "23554252352542343",
          "activePerspective": ".Beta",
          "perspectives": [
            {
              "type": ".Beta",
              "activeLayout": "1x1",
              "layouts": [
                {
                  "caption": "1x1",
                  "canonicalName": "1x1",
                  "icon": {
                    "source": "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"18\" height=\"18\"><path fill=\"none\" stroke=\"#fff\" class=\"eveInteractiveSvgStroke\"/></svg>"
                  },
                  "placement": {
                    "center": {
                      "config_mode": ".Default",
                      "visualization": "object-table",
                      "configuration": "punkt"
                    }
                  }
                }
              ]
            }
          ]  
       }

CodePudding user response:

You probably want to set bodyValue as an object (before passing in)

const bodyValue = { abc, abc, abc }

then in the request, as per first attempt

body: bodyValue

It's hard to tell because even the working "pasted in" example has syntax errors - there should be commas between each property.

CodePudding user response:

@Fody this is not much different than your answer.

var body = {abc, abc, abc}

and inside cy.request

  url: "xxx",
method: 'PUT',

headers: {
  authorization: cookies
},

body

And it worked.

  • Related