1

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?

Panpaper
  • 451
  • 1
  • 6
  • 16

2 Answers2

3

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);
}
Panpaper
  • 451
  • 1
  • 6
  • 16
0
var currentUrl=''

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

cy.visit(currentUrl)
  • 2
    See "[Explaining entirely code-based answers](https://meta.stackoverflow.com/q/392712/128421)". While this might be technically correct, it doesn't explain why it solves the problem or should be the selected answer. We should educate along with helping solve the problem. – the Tin Man Mar 22 '22 at 05:01