15

I would like to know how to capture and read the URL after a click event on an <a> link.

On the onClick event our javascript does some string manipulation of the actual href of the clicked link and then a window.location.href = myNewReplacebleURL is done on the fly. The original href is not necessarily the location you get to after the onClick.

Here is how I started:

describe("Twitter", function() {

  it("Should assert that via value is set correctly in JS", function() {

    cy.server();
    cy.visit(Cypress.config("appUrl") + "/probes/sha/sha-via.html");
    cy.get("#v_test ul.share li a")
      .click();

  });

});

EDIT: What I would like is to catch the URL located at the "Page Load" step.

enter image description here

Radu Chiriac
  • 1,374
  • 3
  • 18
  • 34

2 Answers2

11

You should be able to use cy.on to perform your assertions inside the url:changed event callback:

cy.on("url:changed", (newUrl) => {
  expect(newUrl).to.contain("?magic=true")
})
conny
  • 9,973
  • 6
  • 38
  • 47
Guillaume Robbe
  • 658
  • 1
  • 7
  • 18
  • 1
    I had to use this approach to catch query params changes, but I don't get it. Usually, Cypress philosophy is to retry until your assertion work, so `cy.url().should("match", "?foo=bar")` would be expected to wait for the url to match "foo=bar". It is not the case, I have to listen to  `url:changed` as you described to make it work. – Eric Burel Jan 13 '21 at 07:36
5

You can use thecy.location() command, example:

cy.get("#v_test ul.share li a")
      .click();
cy.location('href').should('eq', 'newUrl');

Also, as an alias to the cy.location('href') command you could use cy.url().

Diogo Rocha
  • 9,759
  • 4
  • 48
  • 52