Search code examples
javascriptcypressmocha.jsresponsechai

Cypress/JavaScript: Parameter on request path (response.body.VARIABLE)


Was trying to figure out how to pass a variable on a response path like this

response.response.body.data.groupsData.hereGoesTheVariable

Where the variable is one of the attributes like name, id, etc. This way I can create a function and just pass the desire attribute.

I was trying template literals and so but with no affect. Any idea?

I'm getting the response from

 cy.wait('@' + alias).then(response => {
const text = response.response.body.data.groups.attribute; });

Solution

  • Properties can be accessed using dot notation like:

    response.response.body.data.groupsData
    

    or by bracket notation like

    response.response.body.data["groupsData"]
    

    where the thing in the brackets is a string, or a variable.

    So, if hereGoesTheVariable is your variable,

    const hereGoesTheVariable = 'somePropertyName';
    const text = response.response.body.data.groupsData[hereGoesTheVariable]
    

    this is equivalent to

    const text = response.response.body.data.groupsData.somePropertyName