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.
CodePudding user response:
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);
});
CodePudding user response:
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 !