Home > Software design >  How to save just part of URL in Cypress (without domain name)
How to save just part of URL in Cypress (without domain name)

Time:10-13

I'm writing CY test and was trying to solve it by myself for couple of hours but unsuccessfully. Could you please help me here a bit :)

Each time I run the test I'm getting new URL, e.g.

https://website.com/en/info/is/here/

And I need to save only

/en/info/is/here/ (so without domain name)

I need to compare it later with another href.

Could you please advise me the way how to do it or at least the direction? Thanks a lot!

CodePudding user response:

You can use the following :

let firstUrl = null;
let secondUrl = null;
cy.url().then(url => {
   firstUrl = url;
});

/* sometimes later */ 
cy.url().then(url => {
   secondUrl = url;
});

/* sometimes later */ 
expect(firstUrl).to.equal(secondUrl)

If you want to just compare some part of these URL I recommend you using a regex expressions.

CodePudding user response:

You can use the javascript split to do this:

let partUrl
cy.url().then((url) => {
  partUrl = url.split('com')[1] //saves /en/info/is/here/
})

CodePudding user response:

You could use .replace() and the Cypress baseUrl value, and then store that value in a Cypress environment variable.

cy.url().then((url) => {
  Cypress.env('someUrl', url.replace(Cypress.config('baseUrl'), '');
}).then(() => {
  cy.log(Cypress.env('someUrl');
})
  • Related