mercredi 14 avril 2021

How can I update a global variable in Cypress tests?

I want to use a Global variable inside my Cypress test file but its value isn't changing as expected despite adding waits.

const builder = {
  stepsArr: []
};
describe('my test', () => {
  beforeEach(() => {
    cy.intercept('/graphql', (req) => {
      req.continue((res) => {
        if (res.body.data?.steps) {
          builder.stepsArr = res.body.data.steps.steps;
          console.log({ stepsArr: builder.stepsArr }); // logs correctly!
        }
      });
    }).as('graphqlRequest');
  });
  it.only('should check global var', () => {
    cy.waitFor('steps');
    cy.wrap({ getStepByTitle: pathwayBuilder.getStepByTitle })
      .invoke('getStepByTitle', {
        steps: builder.stepsArr // always empty array!
      })
      .then((stepObj) => {
        cy.log(stepObj);
      });
  });
});

The order of execution is correct but the value of Global variable isn't updating. Its showing empty array when I invoke my function despite retrying for like 100 times. What could be wrong?

cy.waitFor('steps'); is from a command in support/commands.js file

Cypress.Commands.add('waitFor', operationName => {
  cy.wait('@graphqlRequest').then(({ request }) => {
    if (request.body.operationName !== operationName) {
      cy.log('Waiting for:', operationName)
      return cy.waitFor(operationName)
    }
    return null
  })
})

The function just logs the parameters on console

exports.pathwayBuilder = {
    getStepByTitle: (title, steps) => {
        console.log("Search", title);
        console.log("Steps", steps); // empty!
   }
}

Aucun commentaire:

Enregistrer un commentaire