Dealing with multiple redirects in Cypress

January 25th, 2021
2 min read

Let’s take a look into our very simple app. Clicking on out "Let’s go!" button will redirect us to page2.html. This second page has an immediate redirect to page3.html

The whole thing happens very fast, but when you look closely you can see the redirect happening for a brief second in the address bar. Let’s now write a test for all of our redirects, so that we know that the middle one actually happens. Our test will look like this:

Copy to clipboard

When we run our test though, we can see that the test fails. Our redirect happens just too fast. Since Cypress waits for page to fully load, our assertion comes in too late and our test fails.

We see Cypress registering this redirect event, so it seems like it is something we should be able to test. And it’s true. This is one of the events we can look into in our test. Whenever a url is changed, this event is registered. Using cy.on command we can catch the event called url:changed. This event returns the url which we are being redirected to, so we can feed this into an array of all our redirects and test our array instead, like this:

Copy to clipboard

Instead of using .location() command, we are now just testing our urlRedirects array. We need to use .then() command, otherwise our assertion would be ran before our array is filled with values.

Hope this helps!

Let’s keep in touch

From time to time I send some useful tips to your inbox and let you know about upcoming events. Sign up if you want to stay in loop.

is required.

I treat your email address like I would my own. That means no ads. Just notifications of when I do cool stuff. Unsubscribe anytime. Click here to read about how I handle your data