Narine Poghosyan
Narine Poghosyan

Reputation: 893

How can I check URL content with Cypress

I want to check my URL content and do something like this:

if (URL.include('path')) {
  //do something 
} else {
  // do something else
} 

I can check my URL like this

cy.url().should('include', 'path');

but when I am pasting it in if operator it is not working.

Upvotes: 14

Views: 29686

Answers (3)

Alex Izbas
Alex Izbas

Reputation: 625

Will recommend you to use .includes() method. It determines whether a string contains the characters of a specified string:

const path = 'user/survey';

cy.url().then(($url) => {
    if($url.includes(path)) {
        cy.log("Yes")
    } else  {
        cy.log("No")
      }
})

Upvotes: 14

Narine Poghosyan
Narine Poghosyan

Reputation: 893

I found The answer, but its vary long. Any ideas pls.

      cy.url().then(url => {
         const currentURL = url.split('/path/');
         const pathURL = currentURL[1];
         if(pathURL === 'user/survey')
         {
            cy.log('aaaaaaaaaa')
         } else {
            cy.log('bbbbbbbbb')
         }
     })

Upvotes: 2

François
François

Reputation: 2241

You can combine location() with then().

Here is how I do it:

    cy.location('pathname').then((loc) => {
        if(loc == '/my/path') {
            ...do
        } else {
           ...smth else
        } 
    })

I hope it solves your issue, Best

Upvotes: 3

Related Questions