Home > front end >  How to iterate through the all the body objects
How to iterate through the all the body objects

Time:02-11

I want to assert if my response.body does not contain some provided value. The body has let's assume 10 objects. All the objects have "id" field. How to use some kind of each or forEach on the request response? I know that I can use e.g.

expect(response.body[0].requestId).not.eq(value);
expect(response.body[1].requestId).not.eq(value);
expect(response.body[2].requestId).not.eq(value);
expect(response.body[3].requestId).not.eq(value);

but I don't know how to code it in a more optimized way.

I prepared the array with:

    const bodyObjects = [
      'body[0]',
      'body[1]',
      'body[2]',
      'body[3]',
      'body[4]',
    ];
    

My code

it.only("Something "A" should not see something "B"", () => {
    const bodyObjects = [
      'body[0]',
      'body[1]',
      'body[2]',
      'body[3]',
      'body[4]',
    ];
    cy.request({
      method: "POST",
      url: Cypress.env("URL",
      auth: {
        bearer: token,
      },
      body: {
        id: someId,
      },
    }).then((response, $bodyObjects) => {
      responseId = response.body.id;
      expect(response.status).to.eq(201);
      **MY POTENTIAL ASSERTION**
    })
  });

CodePudding user response:

You can apply a forEach like this:

it.only('Something "A" should not see something "B""', () => {
  const bodyObjects = ['body[0]', 'body[1]', 'body[2]', 'body[3]', 'body[4]']
  cy.request({
    method: 'POST',
    url: Cypress.env('URL'),
    auth: {
      bearer: token,
    },
    body: {
      id: someId,
    },
  }).then((response, $bodyObjects) => {
    responseId = response.body.id
    expect(response.status).to.eq(201)
    bodyObjects.forEach((bodyObject) => {
      expect(response[bodyObject].requestId).not.eq(value)
    })
  })
})

CodePudding user response:

Considering response.body is an array, you can use a forEach loop to iterate through them:

responde.body.forEach(res => {
  expect(res.requestId).not.eq(value)
})
  • Related