4

I am getting to grips with Cypress. Loving it so far, however, I have got stuck with the following.

I want to test that when a button is clicked, the user is directed to the correct external site. This works fine (at the moment) using the following code:

$("#my-button").click(function() {
  var external_url = 'https://www.somesite.com/';
  if($("#my-checkbox").prop("checked")) {
    external_url += 'foo';
  } else {
    external_url += 'bar';
  }
  window.location.href = external_url;

  return false;
});

Starting small within a Cypress spec:

it('Should direct to external site depending on checkbox state', () => {
  cy.get('#my-button').click()
})

Receives Cypress Error: Cypress detected a cross origin error happened on page load:

Blocked a frame with origin "http://localhost:8888" from accessing a cross-origin frame.

This is fair enough, and I understand why I get the error. I don't want to disable Chrome Web Security to get around it.

Can someone show me how I should test this use case?

I think I should be trapping the location change with cy.stub() and/or cy.on() but so far I have not had success:

it('Should direct to external site depending on checkbox state', () => {
  cy.stub(Cypress.$("#my-button"), "click", () => {
    console.log('stub')
  })

  cy.on("window.location.href", win => {
    console.log('on')
  })

  cy.get('#my-button').click()
})

The button click still results in the error being thrown as the script still attempts to set the location to an external site.

adey_888
  • 316
  • 1
  • 6
  • Was there a particular reason for not wanting to disable the Web Security? https://docs.cypress.io/guides/guides/web-security.html#External-Navigation Cypress recommends checking the href value as an alternative. – atlas_scoffed Mar 03 '21 at 23:42
  • [This answer](https://stackoverflow.com/a/71277156/17865804) might help. – Chris Oct 17 '22 at 10:18

0 Answers0