Skip to main content
Cypress App
End-to-End Only

location

Get the URL of the page that is currently active as a location object, or one part of that URL.

Syntax​

cy.location()
cy.location(key)
cy.location(options)
cy.location(key, options)

Usage​

Correct Usage

cy.location() // Get location object
cy.location('host') // Get the host of the location object
cy.location('port') // Get the port of the location object

Incorrect Usage

cy.get('a').location() // Ignores the link, yields the page's location
cy.location('assign') // Errors, the location object has no assign key

cy.location() reads the page's URL, not an element's href. To check where a link points, assert on the link's own properties instead:

cy.get('a').should('have.prop', 'pathname', '/users')

Arguments​

key (String)

One of the properties listed under Yields, such as 'pathname'. cy.location() yields that property's value instead of the full location object, and fails when the location object has no property named key.

options (Object)

Pass in an options object to change the default behavior of cy.location().

OptionDefaultDescription
logtrueDisplays the command in the Command Log
timeoutdefaultCommandTimeoutTime to wait for cy.location() to resolve before timing out

Yields ​

cy.location() is a query, and it is safe to chain further commands.

When not given a key argument​

cy.location() yields a plain object with these properties. The example values are for the URL https://example.com:8080/app/users?tab=1#section.

PropertyTypeExample value
hashstring'#section'
hoststring'example.com:8080'
hostnamestring'example.com'
hrefstring'https://example.com:8080/app/users?tab=1#section'
originstring'https://example.com:8080'
pathnamestring'/app/users'
portstring'8080'
protocolstring'https:'
searchstring'?tab=1'
searchParamsURLSearchParamssearchParams.get('tab') returns '1'

When given a key argument​

  • cy.location() yields the value of that property: a string, or a URLSearchParams object for searchParams
  • cy.location() fails when the location object has no property named key

These diagrams show where each key sits in a URL:

Diagram of the URL https://example.com:8080/app/users?tab=1#section split into its parts: protocol is https:, hostname is example.com, port is 8080, host is example.com:8080, origin is https://example.com:8080, pathname is /app/users, search is ?tab=1, hash is #section, and href is the whole URL.

In a hash-based route, a query string after the # is part of the hash:

Diagram of the hash-based route https://example.com/app/#/users/1?tab=profile split into its parts: pathname is /app/ and hash is #/users/1?tab=profile. The question mark is inside the hash, so search is an empty string.

Examples​

Key argument​

Assert that a redirect works​

Grab only the pathname and add an assertion.

cy.visit('http://localhost:3000/admin')
cy.location('pathname').should('eq', '/login')

Wait longer for a slow redirect​

Pass a timeout when a redirect takes longer than defaultCommandTimeout, such as after a login request. Cypress retries the assertion until the pathname matches or the timeout passes.

cy.get('[data-cy="login"]').click()
cy.location('pathname', { timeout: 10000 }).should('eq', '/dashboard')

Match a pathname that contains a generated ID​

When your application creates a record and navigates to it, the ID in the URL isn't known ahead of time. Match the pathname against a regular expression instead.

cy.get('[data-cy="create-user"]').click()
cy.location('pathname').should('match', /^\/users\/\d+$/)

Save part of the URL for later in the test​

Transform the value in .then() and save it with .as() to use it in a later command.

cy.location('pathname')
.then((pathname) => pathname.split('/').pop())
.as('userId')

cy.get('@userId').then((userId) => {
cy.request(`/api/users/${userId}`).its('status').should('eq', 200)
})

No arguments​

Make assertions about every location property​

cy.visit('http://localhost:8000/app/index.html?q=dan#/users/123/edit')

cy.location().should((loc) => {
expect(loc.hash).to.eq('#/users/123/edit')
expect(loc.host).to.eq('localhost:8000')
expect(loc.hostname).to.eq('localhost')
expect(loc.href).to.eq(
'http://localhost:8000/app/index.html?q=dan#/users/123/edit'
)
expect(loc.origin).to.eq('http://localhost:8000')
expect(loc.pathname).to.eq('/app/index.html')
expect(loc.port).to.eq('8000')
expect(loc.protocol).to.eq('http:')
expect(loc.search).to.eq('?q=dan')
expect(loc.searchParams.get('q')).to.eq('dan')
})

Check location for query params and pathname​

Pass a callback to .should() to work with the location object directly. Cypress retries the callback until every assertion in it passes.

index.html
<form action="/users">
<input id="search" name="search" />
</form>
spec.cy.js
cy.visit('http://localhost:3000/')
cy.get('#search').type('niklas{enter}')
cy.location().should((loc) => {
expect(loc.search).to.eq('?search=niklas')
expect(loc.pathname).to.eq('/users')
})

Query parameters​

Read a query parameter​

searchParams yields a URLSearchParams object, so you can call its methods with .invoke().

cy.visit('http://localhost:3000/users?page=2&sort=name')
cy.location('searchParams').invoke('get', 'sort').should('eq', 'name')

Assert on query parameters in any order​

Comparing search to a string fails when your application writes the same parameters in a different order. Asserting on searchParams checks each parameter by name, and getAll() reads a parameter that appears more than once.

cy.visit('http://localhost:3000/posts?sort=name&tag=cypress&page=2&tag=testing')
cy.location('searchParams').should((params) => {
expect(params.get('page')).to.eq('2')
expect(params.get('sort')).to.eq('name')
expect(params.getAll('tag')).to.deep.eq(['cypress', 'testing'])
})

Cross-origin redirects​

Assert that sign-in redirects to an identity provider​

cy.location() reads the URL after your application navigates to another origin, so you can confirm where a sign-in flow landed before you interact with that page inside cy.origin().

cy.visit('http://localhost:3000/')
cy.contains('a', 'Sign in').click()

cy.location('origin').should('eq', 'http://auth.example.com')
cy.location('searchParams')
.invoke('get', 'redirect_uri')
.should('eq', 'http://localhost:3000/callback')

cy.origin('http://auth.example.com', () => {
cy.get('input[name="email"]').type('[email protected]')
})

Notes​

cy.location() yields a plain object, not window.location​

cy.location() reads the current URL of the application under test from the browser and yields a plain object with the properties listed under Yields. It has none of the window.location methods, such as assign() or reload(). Read href when you need the full URL as a string.

Changing a property on the real window.location object navigates the browser away. Changing a property on the object cy.location() yields has no effect on navigation.

Logging the yielded object shows only its URL properties:

cy.location().then((loc) => {
console.log(loc)
})
DevTools console showing the plain object cy.location() yields, with hash, host, hostname, href, origin, pathname, port, protocol, search, and searchParams

Cross-origin pages and cy.location()​

Cypress reads the URL through the browser's automation protocol instead of the application's window, so cy.location() works after your application navigates to another origin, without wrapping it in cy.origin(). See Assert that sign-in redirects to an identity provider.

Choosing between cy.location(), cy.url(), and cy.hash()​

All three commands read the same URL from the browser. Use the one that yields what you're asserting on:

  • cy.url() yields the full URL as a string, the same value as cy.location('href')
  • cy.hash() yields the fragment, the same value as cy.location('hash')
  • cy.location() yields any other part of the URL, such as pathname, host, or searchParams, or the whole location object

In a hash-based route, a query string after the # belongs to the hash, so search and searchParams don't include it. See Query strings inside a hash route.

Pass a key instead of chaining .its()​

cy.location('pathname') and cy.location().its('pathname') both retry until the assertion that follows passes. Passing the key reads more clearly and shows the key next to location in the Command Log.

cy.location('pathname').should('eq', '/users')

Rules​

Requirements ​

  • cy.location() requires being chained off of cy.

Assertions ​

  • cy.location() automatically retries until all chained assertions have passed

Timeouts ​

  • cy.location() can time out waiting for the browser to report the page's URL.
  • cy.location() can time out waiting for assertions you've added to pass.

Command Log​

Assert on the location's href

cy.location().should((loc) => {
expect(loc.href).to.include('commands/querying')
})

The commands above display in the Command Log as:

Command Log showing a location command followed by an assertion that the href includes commands/querying

When clicking on location within the Command Log, the console outputs the following:

DevTools console after clicking the location command, showing Command: location and the Yielded location object

History​

VersionChanges
15.18.1Experimental WebKit yields the same location object as other browsers
15.0.0In Chromium-based browsers and Firefox, reads the URL through the browser's automation protocol. The yielded object includes searchParams and no longer includes toString

See also​