0
0
Cypresstesting~5 mins

cy.location() for URL parts in Cypress

Choose your learning style9 modes available
Introduction

We use cy.location() to check parts of the web page URL during tests. It helps us make sure the page is where we expect it to be.

To verify the current page URL after clicking a link.
To check if the user is redirected to the correct page after login.
To confirm query parameters are present in the URL after a search.
To test if the URL path changes correctly when navigating through the app.
To ensure the protocol (http or https) is correct for security checks.
Syntax
Cypress
cy.location([options])

// options can include { timeout: number }

// To get a specific part of the URL:
cy.location('pathname')
cy.location('hostname')
cy.location('protocol')
cy.location('search')
cy.location('hash')

cy.location() returns a Location object representing the current URL.

You can pass a string to get a specific part like 'pathname' or 'hostname'.

Examples
Check that the URL path is exactly '/home'.
Cypress
cy.location().should((loc) => {
  expect(loc.pathname).to.eq('/home')
})
Check that the hostname part of the URL is 'example.com'.
Cypress
cy.location('hostname').should('eq', 'example.com')
Verify the URL uses HTTPS protocol.
Cypress
cy.location('protocol').should('eq', 'https:')
Check that the URL query string includes '?q=testing'.
Cypress
cy.location('search').should('include', '?q=testing')
Sample Program

This test visits a URL and checks that the path is '/home' and the protocol is 'https:'.

Cypress
describe('URL parts test', () => {
  it('checks URL pathname and protocol', () => {
    cy.visit('https://example.com/home?user=123')
    cy.location('pathname').should('eq', '/home')
    cy.location('protocol').should('eq', 'https:')
  })
})
OutputSuccess
Important Notes

Use cy.location() inside a test after navigation or actions that change the URL.

Remember that cy.location() commands are asynchronous and return chainable Cypress objects.

Use assertions like .should() to verify URL parts.

Summary

cy.location() helps check parts of the current URL in tests.

You can get specific parts like pathname, hostname, protocol, search, and hash.

Use it to confirm navigation and URL changes work as expected.