Emma Strong
Emma Strong

Reputation: 43

Cypress get URL as a string to use in next commands not working

I am trying to get the url as a string in Cypress. Here is my code:

 let schoolDistrictViewLink1 = null;
 cy.url().then(($url) => { schoolDistrictViewLink1 = $url, cy.log($url)})
 cy.log(schoolDistrictViewLink1)

When I run the test, the first log properly logs the url, but schoolDistrictViewLink1 is still null.

I cannot get schoolDistrictViewLink1 to equal the url.

Upvotes: 4

Views: 924

Answers (3)

jjhelguero
jjhelguero

Reputation: 2565

If you are looking to chain commands immediately to cy.url then you will not have to do anything just chain.

cy.url()
  .should('eq', 'https://www.website.com/')

If you want to use it at a later point in your test you can use a combination of function() and this keyword

let url
it('check url', function(){
  cy.url().then( u => url = u)
  // later in your test
  cy.get('selector').should('have.text', this.url)
})

Upvotes: 1

tlolkema
tlolkema

Reputation: 288

This will not work because of the asynchronous nature of Cypress. Cypress themselves advises to use aliases to save values for later use.

https://docs.cypress.io/guides/core-concepts/variables-and-aliases

In you example you can put the value of cy.url() in an alias. Which you can get via cy.get('@aliasName') later:

Example:

    cy.url().as("schoolDistrictViewLink1");

    // do other things

    // when you need to use the value
    cy.get("@schoolDistrictViewLink1").then((url) => {
      cy.log(url);
    });

Upvotes: 4

Ishak Hari
Ishak Hari

Reputation: 188

Explanation of the problem:

you are trying to assign the value of the URL to schoolDistrictViewLink1 in a callback function passed to cy.url(). This means that the value of schoolDistrictViewLink1 will not be updated until the callback function is called, which happens asynchronously after cy.url() is executed.

Solution:

you can use the async/await pattern to wait for the value to be updated.

async function getUrl() {
  let schoolDistrictViewLink1 = null;
  await cy.url().then(($url) => { schoolDistrictViewLink1 = $url, cy.log($url)});
  return schoolDistrictViewLink1;
}

const url = await getUrl();
cy.log(url);

Happy coding !

Upvotes: -1

Related Questions