App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Home Guide How to handle Errors in Cypress

How to handle Errors in Cypress

By Ganesh Hegde, Community Contributor -

Table of Contents

What is an Exception (Error) in Cypress?

An Exception or an Error is an abnormal event, which may break the normal flow of test script execution, in turn causing the tests to fail. In Cypress, exceptions may be originated from the Application/Webpage Under Test or may be originated from your automation script.

Handling Error in Cypress

Unlike other Javascript-Based Frameworks, Cypress doesn’t allow you to use the try and catch block to handle the exception. Cypress provides a special mechanism for handling exceptions in your code.

Handling different types of Exceptions such as:

  1. Exception from Webpage Under Test
  2. Exception within the code
  3. Exception due to unexpected status code

Handling Exception from Webpage Under Test in Cypress

Consider a scenario, where you are navigating to one of the web pages, which is throwing exceptions. 

For example, navigating https://wxyz.in throws 

Uncaught SyntaxError: Unexpected token '<'

This has nothing to do with your test, but still, the test would fail due to the resulting webpage throwing error.

Handling Exception from Webpage Under Test in Cypress

Handling Exceptions within the Code in Cypress

Executing the above test script in Cypress causes the test to fail with the error message “The following error originated from your application code, not from Cypress.”

Exceptions within the Code in Cypress

As mentioned earlier, using a try-catch block doesn’t help. To handle the error from the Web page under test, cypress provides the special command 

cy.on('uncaught:exception', (err, runnable) => {})

This command always listens to the exceptions return false and will ignore these errors from failing tests. The above command can be modified to catch the exception as seen below.

describe('Exception Handling In Cypress', () => {

    it('Navigate to webpage',()=>{

        cy.on('uncaught:exception', (err, runnable) => {

            return false

        })

        cy.visit('https://www.wxyz.in');

    })

})

Handling Exceptions within the Code in Cypress 1

Validate Specific Exceptions

It is not good to ignore all the exceptions, there are chances you may miss the important bugs in your application so it is always recommended to handle only known exceptions.

The err.message provides the full exception message, you need to validate using if condition. Modify the code to handle specific Exceptions as seen below

describe('Exception Handling In Cypress', () => {

    it('Navigate to webpage',()=>{

        cy.on('uncaught:exception', (err, runnable) => {

            if(err.message.includes('Unexpected token')){

               console.log('Application Error Javascript Token')

               return false;

            }

            return true

        })

        cy.visit('https://www.wxyz.in');

    })

})

In the above code, If the ‘Unexpected token‘ error is thrown in the application, Cypress ignores it, if there is any other exception thrown then it will mark the test as a fail.

Handling Failure Exception in Cypress

The above method handles only uncaught exception scenarios, it doesn’t handle the exception which is caused by your test script or automation code. 

Scenario: You might have to click on the button, but it might not exist

Cypress throws an error stating that “Timed out retrying after 4000ms: Expected to find element: #buttondoestexist, but never found it.”

describe('Exception Handling In Cypress', () => {

    it('Navigate to webpage',()=>{

        cy.visit('https://www.google.in');

        cy.get('#buttondoestexist')

    })

})

 

Failure Exception in CypressTo handle the above exception, you need to use the following Cypress command 

Cypress.on('fail', (error, runnable) => {}

Modify the above code to handle the exception as seen below

describe('Exception Handling In Cypress', () => {

    it('Navigate to webpage', () => {

        Cypress.on('fail', (error, runnable) => {


        })

        cy.visit('https://www.google.in');

        cy.get('#buttondoestexist')

    })

})

The above code enables us to pass the test even if there is an exception. However, in a real-world scenario, one has to handle different types of exceptions. 

Here, error handling requires diligent selection based on the use case, for example, pass the test only for “buttondoestexist” error when the button to be clicked does not exist. 

In such cases, you can modify the code to handle the exception for a specific scenario.

describe('Exception Handling In Cypress', () => {

    it('Navigate to webpage', () => {

        Cypress.on('fail', (error, runnable) => {

            if (!error.message.includes('buttondoestexist')) {

                throw error

            }

        })

        cy.visit('https://www.google.in');

        cy.get('#buttondoestexist')

    })

})

If you execute the test it will be marked as a pass though there is an exception.

Handling Failure Exception in Cypress

Handing Exception due to Unexpected Status Code in Cypress

Cypress is designed in a way that, if the web page returns any state code other than 200, then it will throw an exception. Consider Scenario, you wanted to test the status code of some website other than 200 (Negative scenarios). In this case, you need to handle the exception to avoid unwanted test failures. 

Cypress provides the option failOnStatusCode: false, where you need to pass this option to cy.visit() command.

Example: Webpage throwing 400 Bad requests.

describe('Exception Handling In Cypress', () => {

    it('Navigate to webpage', () => {

        cy.visit('https://somewebsitethrows400.com/r/files')

    })

})

Exception due to Unexpected Status Code in Cypress

Cypress code to handle status code exception:

describe('Exception Handling In Cypress', () => {

    it('Navigate to webpage', () => {

        cy.visit('https://somewebsitethrows400.com/r/files',{failOnStatusCode: false})

    })

})

Handling Exception due to Unexpected Status Code in Cypress

Errors are very common in web applications, which might even occur due to browser compatibility as well. Since a webpage renders differently on different browser versions. However, It is important to check the browser compatibility with different operating systems. Usually, browser compatibility errors are caught during cross-browser testing

Setting up the required infrastructure for cross-platform testing is very time-consuming and involves a lot of cost and effort. However, using a real device cloud, like BrowserStack provides access to 3000+ real devices and browsers ensuring a comprehensive test coverage under real user conditions

Considering the access to a wide range of devices and browsers among the user base, it is advisable to have wider cross compatibility for a seamless and consistent user experience. Moreover, testing on a large number of devices can be done in a short period of time by leveraging Test Automation frameworks like Cypress, and parallel testing for accelerated test cycles.

Run Cypress Tests on Real Devices

Tags
Automated UI Testing Automation Frameworks Automation Testing Cypress

Featured Articles

Cypress Web Testing Framework: Getting Started

How to handle Click Events in Cypress

Curated for all your Testing Needs

Actionable Insights, Tips, & Tutorials delivered in your Inbox
By subscribing , you agree to our Privacy Policy.
thank you illustration

Thank you for Subscribing!

Expect a curated list of guides shortly.