How to test redirect with Cypress
By Hamid Akhtar, Community Contributor - May 10, 2023
What is Redirecting to a different URL?
A redirection is used to move users to another URL. The first URL is the one that the user clicks, types, or otherwise asked. The second is the new destination URL that the user will be redirected to. Redirections work basically the same way for search engines.
They guide the search engines from one URL to another. Redirects are frequently set up by website owners for sites that have broken links, duplicate content or have been moved to new URLs. Users and search engines can then obtain the most pertinent or recent page.
- What is Redirecting to a different URL?
- Cases / Scenarios where you have to redirect the user to a new URL
- Why it is important to Test Redirect to a new URL with Cypress
- Redirects 301 code
- Found Page 200 code
- Not Found Page 404 code
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:
- In the event that the original URL is no longer active, forward traffic to the new URL.
- Shift authority when backlinks lead to a relocated page
- Enhance the general user experience by preventing visitors from landing on broken or duplicated pages.
- The loss of search engine rankings and customer dissatisfaction can result from neglecting to use redirects.
- 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.
- You eliminate a page.
- Parent sites or category tags you add have an impact on URLs.
- Your page is transferred to a new domain.
- Your website is undergoing repair.
- Combining two or more identical web pages
- Your website is converted from HTTP to HTTPS.
Read More: How to find Broken Links using Cypress
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
- 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.
Also Read: How to change Cypress baseURL in test?
Closing Notes
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 support you in performing these verifications is Cypress. And with this, if you’re using a content management system (CMS) like WordPress, Ghost, or a number of others, it can be a quick and simple way to ensure all redirects are functioning properly.
Cypress testing can be performed on 30+ actual browser versions on Windows and macOS. By simulating actual user actions, BrowserStack Automate can help you find problems in software before your customers do.
For software to function under real-world conditions like a low battery, incoming calls, slow network conditions, etc., actual devices must be used in the testing process. Select a real device cloud that provides a wide range of real devices if an in-house digital lab is not available.
BrowserStack allows you to run your Cypress Tests on 3000+ real devices and browsers and get the most accurate test results. It enables you to test on real desktop and mobile devices for a comprehensive testing experience.