How to test redirect with Cypress

Explore how to automate redirect testing with Cypress to ensure seamless user navigation and flawless web flows.

Get Started free
How to test redirect with Cypress
Home Guide How to test redirect with Cypress

How to test redirect with Cypress

URL redirection is a standard technique in web development that sends users from one address to another, often due to changes in page structure, authentication requirements, or legacy link handling.

While redirects are easy to implement, failing to test them properly can cause users to land on the wrong page, encounter unexpected behavior, or trigger SEO issues.

This article explains how to test URL redirects using Cypress. It covers redirection, when it occurs, why it matters, and how to validate response codes like 301, 200, and 404. It also outlines best practices for accurate and maintainable redirect testing.

What is Redirecting to a different URL?

Redirecting to a different URL occurs when a web application automatically sends a user from one endpoint to another. This behavior is typically triggered by server-side or client-side logic based on specific conditions, such as user authentication, form submissions, routing changes, or URL restructuring.

Redirects serve multiple purposes, such as managing broken links, consolidating duplicate content, enforcing HTTPS or canonical URLs, and handling site migrations.

From a user perspective, redirects ensure a seamless experience by leading them to the correct content. For search engines, redirects help maintain indexing accuracy and preserve SEO value by transferring link equity from the old URL to the new one.

There are several types of redirects, with the most common being:

  • 301 (Moved Permanently): Indicates that a resource has been permanently moved to a new URL.
  • 302/307 (Found/Temporary Redirect): Used for temporary redirections.
  • Meta Refresh or JavaScript-based Redirects: Client-side methods, generally less SEO-friendly.

Because redirect behavior, especially client-side, can vary across browsers, devices, and network conditions, it’s essential to test redirects in real-world environments.

Cypress, a powerful end-to-end testing framework, helps automate redirect testing, ensuring functionality works as expected. By integrating with tools like BrowserStack, teams can run these tests across a wide range of real browsers and devices, catching environment-specific issues before they affect users.

BrowserStack Automate Banner

Cases / Scenarios where you have to redirect the user to a new URL

Here are some of the scenarios where Redirect to a new URL is most commonly used:

  1. In the event that the original URL is no longer active, forward traffic to the new URL.
  2. Shift authority when backlinks lead to a relocated page
  3. Enhance the general user experience by preventing visitors from landing on broken or duplicated pages.
  4. The loss of search engine rankings and customer dissatisfaction can result from neglecting to use redirects.
  5. Consider moving or deleting a web page without first setting up a redirect. The website will respond with a 404 error for users. Thus making for a frustrating encounter for the user. That detracts from a satisfying interaction for the consumer. When users encounter a 404 error, they may decide to abandon your site.
  6. You eliminate a page.
  7. Parent sites or category tags you add have an impact on URLs.
  8. Your page is transferred to a new domain.
  9. Your website is undergoing repair.
  10. Combining two or more identical web pages
  11. Your website is converted from HTTP to HTTPS.

Why it is important to Test Redirect to a new URL with Cypress

Your app’s end users will only ever access your site through a small handful of predetermined URLs. Alternatively, they may frequently fail to include the “www.” or “s” in “https://,” resulting in an incorrectly formatted URL.

With Cypress test redirect, you can test a variety of tasks that are typically done with 300 or 301 redirects from the servers, as well as test user responses to 404 or 500 forbidden pages.

Redirects 301 code

Redirects typically use the 301 — “Moved Permanently” — code. They are used when a particular website or URL has been moved to another location or reorganized.

const baseUrlTesla = "https://www.browserstack.com/";
const urlHttp = "http://browserstack.com";
it(urlHttp + " end location", () => {
cy.visit(urlHttp);
cy.url().should("eq", baseUrlTesla);
});

it(urlHttp + " redirect", () => {
cy.request({
url: urlHttp,

followRedirect: false, // turn off following redirects

}).then((resp) => {
// redirect status code is 301
expect(resp.status).to.eq(301);
expect(resp.redirectedToUrl).to.eq(baseUrlTesla);
});
});

Found Page 200 code

When the server precisely locates the resource at the URL you indicated in your request, the “200” response code is used for all found pages.

const baseUrlTesla = "https://www.browserstack.com/";
const urlHttpsWww = "https://www.browserstack.com/";

it(urlHttpsWww + " end location", () => {
cy.visit(urlHttpsWww);
cy.url().should("eq", baseUrlTesla);
});

it("200 homepage response", () => {
cy.request({
url: urlHttpsWww,
followRedirect: false,
}).then((resp) => {
expect(resp.status).to.eq(200);
expect(resp.redirectedToUrl).to.eq(undefined);
});
});

Not Found Page 404 code

You will see the most stunning and typical code 404, also known as “not found,” when a page cannot be located.

const baseUrlTesla = "https://www.browserstack.com/";
const url404test = "https://www.browserstack.com/not-a-real-page";

it("404 'not found' response", () => {
cy.request({

url: url404test,

followRedirect: false,
failOnStatusCode: false,
}).then((resp) => {
expect(resp.status).to.eq(404);
expect(resp.redirectedToUrl).to.eq(undefined);
});

cy.visit(url404test, { failOnStatusCode: false });
cy.get(".error-code").should("contain", "404");
cy.get(".error-text").should("contain", "Page not found");
});

Run Cypress Redirect Tests on Real Devices

How to test redirect with Cypress (with example)

Now you’ll construct a verification redirect test case that will be directed at a specified web address. The procedure here is to substitute a new URL and then verify the title.

For testing the redirect feature, use the object structure below. You’ll receive these data later from a JSON file.

{
"title": "TITLE OF THE ARTICLE",
"from": "OLD URL",
"to": "NEW URL"
}

Create a “website-redirect” folder in the “cypress/integration” folder and add a test case to it. This test case validates the redirect feature.

describe("website redirects", () => {
it("webpage redirect", () => {

const page = {
"title": "Why is Espresso preferred for Android UI Testing?",
"from": "https://www.browserstack.com/android-ui-testing-espresso",
"to": "https://www.browserstack.com/guide/android-ui-testing-espresso"
}


cy.visit(page.from, { failOnStatusCode: false });



cy.url()
.should("be.equals", page.to)
cy.title()
.should("include", page.title);

});

});

The page.from value is used in the cy.visit(page.from) function to access a page with a URL. In order to set the extra option for loading the page in the browser, you can use the options parameter. If the response code is not “2XX” or “3XX,” the failOnStatusCode: false wouldn’t fail the test.

To check if the URL was changed following the redirect, you can use cy.url() to get the current URL of the website. By calling cy.title(), you can retrieve the title from the current page’s document.title.

Though effective, this method is hindered by the presence of a page object in your test scenario. Put this page object in a different JSON file so that it can be used as test data. The “fixtures” directory, which is typically used to load a collection of data stored in a file, is already present in the predefined structure of the “cypress” folder. You can put your redirect-data.json file there just fine.

Run Cypress Redirect Tests on Real Devices

[
{

"title": "Why is Espresso preferred for Android UI Testing?",
"from": "https://www.browserstack.com/android-ui-testing-espresso",
"to": "https://www.browserstack.com/guide/android-ui-testing-espresso"
},

{
"title": "How to perform Parallel Test Execution in Appium?",
"from": "https://www.browserstack.com/parallel-test-execution-appium",
"to": "https://www.browserstack.com/guide/parallel-test-execution-appium"
},
...

]

There are several methods to load an array for your test cases when a JSON file is created:

  • A fixed collection of data stored in a file is loaded by the cy.fixture(filePath) function. You can make use of this choice within the test case.
  • The JSON file can be loaded and used for data outside of the test case using the require/import.

The second choice is preferable for you because it allows you to build numerous tests using an array of JSON file objects. In this situation, you can use the name of the page as the test case’s name.

import data from '../../fixtures/redirect-data.json';


describe("website redirects", () => {
data.forEach(pageObj => {

it(`redirect of "${pageObj.title}" page`, () => {

cy.visit(pageObj.from, {failOnStatusCode: false});
cy.url()
.should("be.equals", pageObj.to)
cy.title()
.should("include", page.title);
});
});
});

The titles of the pages will be used in your report when the array contains numerous values.

Best Practices for Testing Redirect in Cypress

To ensure reliable and effective redirect testing in Cypress, consider the following best practices.

  • Best practices for search engine optimization when redirecting a URL include sending the user to pages that are both similar to and pertinent to the original. It’s poor form to send users to pages that are unrelated to the original and serve no useful purpose.
  • Chains of redirects are easy to make and should be avoided. Chain links can cause a lot of extra hops that the user might not even notice, but search engines do. Screaming Frog is a useful instrument for discovering chains of redirects. When Google encounters a certain number of 301 redirects, it stops crawling the site entirely, and the new URL is never displayed.
  • Check to see that all of your internal links have been updated. Having incorrect internal links can considerably slow down a website, so accuracy is essential. Websites should minimize the use of redirects as much as feasible. It’s always possible that lingering links will lead to intractable problems on a website.
  • Do not use soft 404s. A redirect to an unrelated website will be viewed by Google as a soft 404. This indicates that Google won’t transmit page authority and will disregard the redirect.
  • Periodic 404 errors are acceptable. When a page doesn’t exist on a new site’s equivalent, it may be essential to leave it as a 404. When you do have them, it’s good to make a personalized 404 page with contact information or useful links can give a user value.

To validate redirect behavior across different browsers, devices, and operating systems, consider running your Cypress tests on real user conditions using BrowserStack. It offers access to 3500+ real browser and device combinations, supports parallel test execution for faster feedback, and integrates seamlessly with Cypress through its CLI.

This helps teams catch inconsistencies that may not appear in local testing setups and ensures a consistent user experience across platforms.

Talk to an Expert

Conclusion

The ability to reroute visitors is a common feature of many websites. Regular tasks like checking redirects, looking up articles, signing up for newsletters, etc., can be performed quickly and easily with the help of test automation.

One of the many tools that supports you in performing these verifications is Cypress. If you’re using a content management system (CMS) like WordPress, Ghost, or a number of others, this can be a quick and simple way to ensure all redirects are functioning properly.

Cypress tests can be executed on real browser environments across Windows and macOS using BrowserStack. By simulating real user interactions it helps teams identify issues before they reach end users.

To ensure software performs reliably under real-world conditions, such as slow network speeds, low battery, or interruptions like incoming calls, testing on actual devices is essential. If maintaining an in-house device lab isn’t feasible, a real device cloud is the best alternative.

BrowserStack provides access to 3500+ real devices and browsers, allowing teams to run Cypress tests across a wide range of desktop and mobile environments. This ensures accurate, comprehensive testing and a consistent user experience across platforms.

Run Cypress Tests on BrowserStack

Tags
Automation Testing Cypress Website Testing

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord