I love it, Steven. You could simplify this even more
Let's simplify the test step by step. First, let's take a look at getting the article ID from the URL
// Extract the article ID from the URL and alias itcy.location('pathname').then(path=>{// path = "/articles/234234234"constarticleID=path.split('/')[2];cy.wrap(articleID).as('articleID');});
Here is the example page and the test
cy.visit('https://dev.to/pepopowitz/working-with-variables-in-cypress-tests-4097')cy.location('pathname').then(path=>{// path = "/author/blog post title"constarticlePost=path.split('/')[2];cy.wrap(articlePost).as('articleID');});
Let's simplify the above code a little bit. When we get the path variable we call split method on it. We can do this inline using cy.invoke.
cy.visit('https://dev.to/pepopowitz/working-with-variables-in-cypress-tests-4097')// pathname is "/author/blog post title"cy.location('pathname').invoke('split','/').then(parts=>{constarticlePost=parts[2];cy.wrap(articlePost).as('articleID');});
Next, we are getting the second item in the array returned by the split('/') call. We can grab an individual property or array's item using cy.its method.
cy.visit('https://dev.to/pepopowitz/working-with-variables-in-cypress-tests-4097')// pathname is "/author/blog post title"cy.location('pathname').invoke('split','/').its(2).then(articlePost=>{cy.wrap(articlePost).as('articleID');});
Hmm, if we are using then callback to simply wrap the articlePost as an alias, we can directly use cy.as
cy.visit('https://dev.to/pepopowitz/working-with-variables-in-cypress-tests-4097')// pathname is "/author/blog post title"cy.location('pathname').invoke('split','/').its(2).as('articleID');
Let's use the wrapped variable to do something. We can make a request but for simplicity I will just log it
cy.visit('https://dev.to/pepopowitz/working-with-variables-in-cypress-tests-4097')// pathname is "/author/blog post title"cy.location('pathname').invoke('split','/').its(2).as('articleID');cy.get('@articleID').then(id=>cy.log(`article **${id}**`))
I love it, Steven. You could simplify this even more
Let's simplify the test step by step. First, let's take a look at getting the article ID from the URL
Here is the example page and the test
Let's simplify the above code a little bit. When we get the
path
variable we callsplit
method on it. We can do this inline using cy.invoke.Next, we are getting the second item in the array returned by the
split('/')
call. We can grab an individual property or array's item using cy.its method.Hmm, if we are using
then
callback to simply wrap thearticlePost
as an alias, we can directly use cy.asLet's use the wrapped variable to do something. We can make a request but for simplicity I will just log it
This is amazing - thanks for the feedback! I'll find a way to incorporate it, either in the original article or a followup.