Home > Software engineering >  How to grab and store last string of url in Cypress
How to grab and store last string of url in Cypress

Time:01-18

I have a url https://www.xxx/xxxx/xxx/1234. I just need the numbers 1234 and store them in my global variable.

cy.log(this.href.substring(this.href.lastIndexOf('/') 1));

CodePudding user response:

The last part of the URL (the slug) is most easily obtained like this

const url = 'https://www.xxx/xxxx/xxx/1234'

const slug = url.split('/').pop()

expect(slug).to.eq('1234')    // ok

Where you are going to store it depends on how you are going to use it (i.e in the same test, across tests in the same spec file, across spec files).

You mention global variables, that would be something like

let slug;  // define empty global variable

it('gets the slug', () => {
  cy.visit('/')
  cy.url().then(url => slug = url.split('/').pop())

  //log in same test
  cy.then(() => {
    cy.log(slug)          
  })
})

it('uses slug', () => {

  // log in different test
  cy.log(slug)             // logs 1234
})

CodePudding user response:

You can use cy.url() to yield the current URL that Cypress is on. You can then set it as a Cypress environment variable, using Cypress.env().

cy.url().then((url) => {
  Cypress.env('href', url.substring(url.lastIndexOf('/')   1));
});
  • Related