DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk6 min

How to Test Anchor Links With Cypress

Test the behavior that matters: assert an anchor's href, or click it and verify the URL and destination state. Includes fragment, external-link, and generated-anchor examples.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Test an anchor according to what it must do: assert its href to verify the declared destination, or click it and assert the resulting URL and destination state to verify navigation. For a same-page link, check the fragment and its target element. Those checks answer different questions; a single vague “link works” assertion may not.

Choose the behavior your test needs to prove

Before writing a Cypress assertion, decide whether the requirement concerns markup, an interaction, a destination, or a collection of generated links.

As an Amazon Associate I earn from qualifying purchases.

Requirement Useful assertion
The anchor declares the right address Assert the exact href attribute.
Clicking a same-page link moves to a section Click, assert the location hash, and verify the target element.
Clicking an internal link navigates to the right page Click, assert the URL, and verify identifying destination content.
Generated content links are well-formed Iterate the intended links and assert each has a valid-looking href; this does not establish that every destination responds.

Cypress documents clicking a link and checking the URL with cy.url(). Its cy.url() reference explains that it yields the active full URL and retries chained assertions until they pass or time out. A configured baseUrl helps keep route assertions independent of a hard-coded host or port.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Test a same-page fragment link

A fragment such as #pricing identifies a location in the current document. If the interaction matters, click the link and check both the hash and the target. The example assumes the page is already loaded and contains an anchor with that href and an element with the matching ID.

cy.get('a[href="#pricing"]').click()
cy.location('hash').should('eq', '#pricing')
cy.get('#pricing').should('exist')

Alternatively, use an application-owned selector, such as [data-cy="pricing-link"], when that is the stable selector your app provides. Cypress notes that .click() is an action; after clicking, start a new chain from cy for assertions about changed state, since the click may rerender or remove the original element.

A URL hash and an existing target do not prove that the target is visible in the viewport. If scrolling into view is a product requirement, assert that separately with an appropriate visibility or position check; do not treat a location assertion as proof of visibility.

Test internal navigation end to end

For a normal same-origin link, verify the route and an identifying piece of destination content. The page path and heading below are examples; substitute values meaningful to the application.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
it('follows the account link', () => {
  cy.visit('/')
  cy.get('[data-cy="account-link"]').click()
  cy.url().should('include', '/account')
  cy.get('h1').should('contain', 'Account')
})

Checking destination content makes the test stronger than a URL-only check when the requirement is that a user reaches a particular page. Cypress retries the URL assertion, so prefer a meaningful condition to an arbitrary wait.

Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Check an anchor’s declared href

If you need to verify the address written in the markup—not whether navigation succeeds—assert the attribute directly. Cypress recommends this approach for external destinations the test team does not control, because a live third-party site can make navigation tests nondeterministic. See Cypress’s cross-origin testing guide.

cy.get('[data-cy="docs-link"]')
  .should('have.attr', 'href', 'https://docs.example.test/guide')

Use the exact destination when it is stable and relevant. If the application intentionally generates a relative URL or builds links from test data, derive the expected value from that data or assert the relevant path and fragment. Avoid a loose substring check that could also match an incorrect destination.

Handle external and cross-origin destinations

When you do not control the destination

Assert the configured href rather than making the test depend on a remote site being available or unchanged. This verifies what your page offers the user without turning a third party’s uptime or content into a test prerequisite.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When you control the destination

If verifying the destination page is part of the requirement and you control its origin, Cypress documents cy.origin() for running assertions on that origin. Follow the current Cypress cross-origin guide for the supported setup. The guide also notes that secure-to-insecure navigation can fail; do not hide a genuine mixed-content security problem with a test workaround.

Check generated anchors across a page

For content pages or generated navigation, select the intended link set and report enough context to identify failures. This example checks that each selected anchor has an href and rejects values containing the literal text undefined.

cy.get('article a').each(($link) => {
  const label = $link.text().trim()
  expect($link, label).to.have.attr('href')
  expect($link.attr('href'), label).not.to.contain('undefined')
})

This checks link markup, not whether all linked pages resolve over the network. If a page can legitimately have no article links, handle that case deliberately: a query expected to find at least one element may fail before the integrity assertions run. You can scope the check to a page known to contain links, or first distinguish the empty-set case if it is valid for the test.

Keep anchor tests stable and diagnostic

  • Prefer stable, application-owned selectors where available; Cypress’s selector guidance recommends making clear which element a test manipulates.
  • Match the assertion to the requirement: declared href, route or fragment, destination content, or generated-link integrity.
  • After clicking, query the resulting state again from cy rather than depending on the clicked element as the subject.
  • Use retryable assertions against expected URL or DOM state instead of adding fixed delays without a specific need.
  • Keep uncontrolled external services out of navigation dependencies; verify their outgoing href unless reaching them is explicitly under test.

Common failures and fixes

The hash assertion never passes

Confirm that the test clicked the intended anchor and that its href contains the expected fragment. If the link navigates to another route as well as a fragment, assert the appropriate location component or full URL rather than expecting a hash-only value to describe the whole navigation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The target-element assertion fails

Check that the target ID exists in the rendered document and that the selector matches it exactly. If the target is inserted asynchronously, assert the expected DOM condition and allow Cypress’s normal retry behavior to work.

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

The original link is detached after clicking

The click may have triggered a rerender. Start a fresh query from cy for the URL or destination element rather than chaining an assertion on the prior link subject.

An external-link test fails intermittently

If the external page is not under your control, change the test to assert the configured href. If the remote destination must be tested, use the documented cross-origin approach and accept that the destination is a dependency.

A bulk anchor query fails on an empty page

Decide whether zero matching anchors is valid for that page. Scope the check to pages expected to contain links or explicitly account for empty pages before applying per-link assertions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The link has an href but still does not work

An href assertion proves the declared value only. Add a click plus URL and destination-state checks for navigation behavior, or separately test a controlled destination. Do not describe a markup-integrity loop as a network link checker.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

For a screenshot of a page while investigating its rendered state, ScreenshotNeo offers a one-request screenshot API; it does not replace Cypress assertions about anchor behavior. A request with a URL returns an image or PDF. See the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
  • Cookie and consent banners, newsletter popups, and chat widgets are removed before capture; each cleanup step can be turned off.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; responses include X-Page-Verdict and X-Billed headers.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients.
  • The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

Frequently Asked Questions

Does checking an anchor’s href prove that the destination works?

No. It verifies the address declared in the markup. To test navigation, click the link and assert the resulting location and destination state.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should I use cy.url() or cy.location() for a fragment link?

Use cy.location(‘hash’) when the fragment is the specific value you need to check; use cy.url() when you want to assert the full active URL.

Can Cypress confirm that every generated link resolves?

A loop over anchors can validate markup values, but it does not prove that each network destination responds. Test controlled destinations separately if resolution is in scope.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.