Home > other >  cy.request with body keys same as value parameter?
cy.request with body keys same as value parameter?

Time:09-29

Confusing title but I'll keep it simple. Lets say I have a function in cypress that takes multiple values (that will eventually get passed as values in a cy.request function.

Lets say the function is something like

function createPersonByAPI(
    firstName: string,
    lastName: string,
    phone: string,
)

and further down in the function I make a request call:

cy.request({
                url: Cypress.env('API_ENDPOINT'),
                method: 'POST',
                body: {
                    firstName: firstName,
                    lastName: lastName,
                    phone: phone,
                },
            })

So obviously I cannot control the body "keys" that are sent....but the naming convention we have been using for stuff like "First Name" would be firstName which is the same as the key.....will this work? Or is there a better way to do this? (Since it looks kinda confusing and I am not even sure if this will work)

This is typescript with Cypress by the way.

CodePudding user response:

Re-using a previously defined variable in a JSONObject is completely fine, and JavaScript is even intelligent enough to interpret only passing in a variable as a key-value pair. I believe this is called shorthand property naming.

const foo = 'bar';

cy.request({ url: '/foo', body: { foo } } );
// is functionally equivalent to...
cy.request({ url: '/foo', body: { foo: foo } } );
  • Related