webghost
webghost

Reputation: 133

Using env var outside method

Have the following method which simply grabs the current page source. My intention is to get the "doc" variable, store it in an environmental variable for later use. Immediately after the function, I send it to a task which essentially then "console.log's" it to the screen; however, it is undefined. If I move the cy.task() inside the function, it works. Outside the function, it is undefined. Shouldn't the value stored in the .env value retain even after the function ends?

getPageSource() {
    cy.get('html:root').eq(0).invoke('prop', 'outerHTML').then((doc) => {
      Cypress.env('pageSource', doc);

      // cy.task('log', { details: Cypress.env('pageSource') }); // WORKS!
    });

    cy.task('log', { details: Cypress.env('pageSource') }); // DOESN'T WORK!
  }

Anyone have any idea how to retain the value for "doc" even after the function ends? I thought environmental variables would work.

Upvotes: 0

Views: 115

Answers (1)

Brandstetter
Brandstetter

Reputation: 143

Yes the value is correctly defined at the end of the function, but you take the value as at the beginning of the function!

To correct the mistake, just use .then() like this

getPageSource() {
  cy.get('html:root').eq(0).invoke('prop', 'outerHTML')
    .then((doc) => {
      Cypress.env('pageSource', doc)
    })

  cy.then(() => {
    cy.task('log', { details: Cypress.env('pageSource') })
  })
}

Upvotes: 4

Related Questions