'Cypress unable to save current URL with `as`

My web app generates a UUIDv4 for every new 'post', and each post has its own URL like /posts/<uuid>. I'm not able to predict what uuid gets generated, and therefore I'm unable to go back to a specific post that was created earlier during testing.

According to the docs, cy.url() returns the URL as a string. I tried saving the URL using a .as(), but it didn't work:

cy.url().as('postUrl');
// go somewhere else
cy.visit('@postUrl');

// ends up visiting `localhost:3000/@postUrl`

I saw in another SO question that I should use .then on cy.url(), but that didn't work either:

cy.url().then(url => url).as('postUrl');
// go somewhere else
cy.visit('@postUrl');

How do I save the current URL for use later?



Solution 1:[1]

Found the answer buried in later pages of a google search. In order to use the saved URL, use cy.get('@postUrl') and call a .then with a callback that visits that url.

cy.url().as('postUrl');
// go somewhere else
cy.get('@postUrl').then(url => {
  cy.visit(url);
}

Solution 2:[2]

var currentUrl=''

cy.url().then(url => {
    currentUrl = url;
});

cy.visit(currentUrl)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Panpaper
Solution 2 yanjingtui