Category:
Cypress
Cypress gives us access to the current URL through the .location() command.
cy.location();
Extracting the path parameter:
cy.location('pathname');
Extracting the path using index:
cy.location('pathname').then(path => {
// path is the value from the previous command, `location("pathname").
// In our example, the value of `path` is "/path/1234".
const pathparam= path.split('/')[2];
});
Extract the value and store it for future:
Cypress provides a command named .wrap() to accomplish this. .wrap() takes a value and yields it as the result of a command, which can then be chained to any other Cypress commands.
cy.location('pathname').then(path => {
// path is the value from the previous command, `location("pathname").
// In our example, the value of `path` is "/path/1234".
const pathparam= path.split('/')[2];
cy.wrap(pathparam).as('pathparam');
});
Accessing the aliased pathparam
Aliased values can be accessed using another command: .get(). When retrieving values with named aliases, as in our situation, we specify the name with an @ prefix, like this:
cy.get('@pathparam');
We'll chain another .then() command to work with the result of the call to .get():
cy.get('@pathparam').then(pathparam => {
cy.request(`/api/articles/${pathparam}`).then(response => {
expect(response.status).to.eq(200);
// And any other assertions we want to make with our API response
});
});