Home > other >  Cypress: Passing request with "optional" body member
Cypress: Passing request with "optional" body member

Time:09-29

In Cypress if I want to make a cypress request where the request body may differ based on another paremeter what is the best way to do that?

For example lets says depending on a parameter value foo a request body key named bar may or may not exist.

For example if foo exists the cy.request would look like this:

cy.request({
                url: Cypress.env('AN_ENDPOINT_OF_SOME_SORT'),
                method: 'POST',
                body: {
                    name: 'A Value',
                    title: 'Some other value',
                    bar: <This value depends on an optional function parameter>
                    type: <this value depends on foo and is either 1 or 2>
                },
            })

if foo does NOT exist it would look like this:

cy.request({
                url: Cypress.env('AN_ENDPOINT_OF_SOME_SORT'),
                method: 'POST',
                body: {
                    name: 'A Value',
                    title: 'Some other value',
                    type: <this value depends on `foo` and is either 1 or 2>
                },
            })

I THINK I can use a ternary operator for type....but im not sure about making a member completely optional. Cypress complains if I use a ? in front of the member key in typescript....so do I just need to do an if/else with 2 different requests?

CodePudding user response:

Please see Succinct/concise syntax for 'optional' object keys in ES6/ES7?

cy.request({
  url: Cypress.env('AN_ENDPOINT_OF_SOME_SORT'),
    method: 'POST',
    body: {
      name: 'A Value',
      title: 'Some other value',
      ...(foo && {bar}),            // present/absent depending on foo
      type: foo ? 1 : 2             // present but value depends on foo
    },
})

CodePudding user response:

You can conditionally include a property using the spread operator and a ternary operator.

const someVar = true;
const myObj = {
  'foo': 'bar',
  ...(someVar ? { otherVar: true } : {})
}

So, in your example, it would be something like...

cy.request({
    url: Cypress.env('AN_ENDPOINT_OF_SOME_SORT'),
    method: 'POST',
    body: {
      name: 'A Value',
      title: 'Some other value',
      type: <this value depends on foo and is either 1 or 2>,
      ... ( foo ? { some: 'value' } : {} )
    },
  });
  • Related