DEV Community

loading...

Discussion on: Working With Variables In Cypress Tests

Collapse
bahmutov profile image
Gleb Bahmutov

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 it
cy.location('pathname').then(path => {
  // path = "/articles/234234234"
  const articleID = 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"
  const articlePost = 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 => {
  const articlePost = 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}**`))
Collapse
pepopowitz profile image
Steven Hicks Author

This is amazing - thanks for the feedback! I'll find a way to incorporate it, either in the original article or a followup.

Forem Open with the Forem app