Justin Oswald
Justin Oswald

Reputation: 179

cy.url not returning a string as expected

Prior to switching to using a hash router, I had been implementing the cy.url command frequently to assure that links were navigating to the right URL addresses throughout the application. Now that we are using hash routing cy.url no longer yields a string, instead it is yielding a function. Any ideas how to work around this or reasons this is happening?

I was getting errors through out the cypress test runner like:

AssertionError: object tested must be an array, an object, or a string, but undefined given

so I logged the typeof result console.log(typeof(cy.url)) and got function printed to the console.

cy.get(dataCyButtonAttribute)
    .should('be.visible')
    .click()
  console.log(typeof(cy.url))
  cy.url().then(url => {
    const categoryId = url.split(`${linkType}/`)[1]
    const category = url.split('admin/')[1]
    expect(category).to.contain(linkType)
    expect(categoryId).to.equal('new')
  })
}

Upvotes: 5

Views: 5009

Answers (2)

River
River

Reputation: 9

I have encountered the same issue. And my solution as below.

      cy.url().then(($base_url) => {   
        let id =  $base_url.substr($base_url.lastIndexOf('/'),$base_url.length) 
        cy.log("The id is " + id);
       })

It works for me.

Upvotes: 0

Lorn
Lorn

Reputation: 192

This should yield a string:

const returnedUrl = null
cy.url().then(url => {
  returnedUrl = url;
});

Cypress commands are asynchronous and must be followed by .then() in order to yield useful return values.

You can refer to this Github issue for more info: https://github.com/cypress-io/cypress/issues/2150

Upvotes: 7

Related Questions