Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I intercept a window.location.href change and change what happens next?

Tags:

href

cypress

I have a window.location.href change happening in a button onClick event on login, it sends the user to a different subdomain where they will then be redirected to a third party OAuth login flow

I want to just handle user login myself within cypress with mock values when the button is clicked, but how can I prevent the page from hitting my real endpoint?

cy.intercept doesn't seem to be working for this sort of thing, and cy.on doesn't seem like it's the right option either

example button
const goToUrl = () => {
  let url = `${process.env.API}/oauth`
  if (props.siteEntry) url += `?redirect=${props.siteEntry.includes('/authorize') ? process.env.BACKBONE : props.siteEntry}`
  window.location.href = url
}

// ...

return (
  <RaisedButton
    onClick={() => goToUrl()}
  />
)
like image 685
alilland Avatar asked Dec 19 '25 18:12

alilland


2 Answers

You should be able to stub out the window.location as per variation of Deal with window.location.replace.

It's a bit of a monkey-patch on your app, but there is no way to "properly" stub window.location methods or properties because it's protected.

cy.on('window:before:load', (win) => {
  win.__location = {
    href: null
  }
})

cy.intercept('GET', '/', (req) => {
  req.continue(res => {
    res.body = res.body.replaceAll(
      'window.location.href', 'window.__location.href')
  })
}).as('index')

cy.visit('/')       // during page load, window.location is stubbed

cy.wait('@index')

Encountered this issue today and was also searching for an answer. Found it after checking on ways to modify my code to use window.open(), and passing '_self' as an additional argument instead of setting the href property of the location. Documentation can be found here: https://www.w3schools.com/jsref/met_win_open.asp

Switching to window.open('URL_HERE', '_self') allowed me to mock the behavior of window.open() and provide an alias in my cypress test like this:

cy.window().then((win) => {
  cy.stub(win, 'open').as('windowOpen');
});

Then later on in my cypress test I could verify the behavior of window.open(). For example to check what URL was used, you can do a get on the alias, and check what it was called with:

cy.get('@windowOpen').should('be.calledWith', 'URL_HERE');
like image 30
Mac_88_ Avatar answered Dec 22 '25 12:12

Mac_88_