According to the documentation, Cy.url() should produce a string. I wanted to capture the current URL into a variable and then reference it after I run a custom Cypress command.
My question is, if cy.url() and cy.location('href') no longer return strings in 3.0.1
- how do we get that value?
Expecting a string of the current URL; instead an object is received that looks like:
// JSON.stringify(cy.url())
{ "chainerId": "chainer2504", "firstCall": false }
// JSON.stringify(cy.location('href'))
{ "chainerId": "chainer2558", "firstCall": false }
Attempting to log either cy.url()
or cy.location('href')
does not result in a string as indicated by the documentation.
Cypress 3.0.1
Cypress commands are async they do not produce a useful return value.
They've always been this way for all versions.
Read these docs and they will answer your exact question for working with them.
@brian-mann Then you should update your documentation and stop claiming that url()
returns a string?
What's the correct approach to read current url?
// if you need the current url in order to store it and use it later, you may do that:
let currentURL
cy.url().then(url => {
currentURL = url
});
// and then use it later like that
cy.then(() => cy.visit(currentURL))
@dugajean You can create a new issue in our docs to document the cy.url() returns here: https://github.com/cypress-io/cypress-documentation/issues/new. Our documentation is open source and contributions are welcome.
But we have this pretty clearly documented about the async nature of Cypress in our introduction docs as already mentioned here. This is exactly why we use the term 'yields' and not 'returns' https://docs.cypress.io/guides/core-concepts/introduction-to-cypress.html#Commands-Are-Asynchronous
Just curious, under the recommendation of using aliases
, what would be the proper way to chain .as()
so that we could assign cy.url()
to an alias? cy.url().as('myUrl')
does not seem to do the trick
@devonjs You can alias a url. The below test passes:
it('works', () => {
cy.visit('https://example.cypress.io')
cy.url().as('url')
cy.get('@url').should('eq', 'https://example.cypress.io/')
})
it('should be running on the right domain', () => {
cy.url().then((url) => {
cy.log(`Expected to be running on:`);
cy.log(baseUrl);
cy.log(`Actually running at:`);
cy.log(url);
cy.url().should('contains', baseUrl);
});
});
Most helpful comment
@brian-mann Then you should update your documentation and stop claiming that
url()
returns a string?