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 -

An Exception or an Error is an abnormal event that may break the normal flow of test script execution, 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.

How to perform Cypress Error Handling?

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

Handling different types of Exceptions, such as:

  1. Handling Exception from Webpage Under Test in Cypress
  2. Handling Exceptions within the Code in Cypress
  3. Validate Specific Exceptions
  4. Handling Failure Exception in Cypress
  5. Handing Exception due to Unexpected Status Code in Cypress

Let’s do through each type in detail below.

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 Cypress uncaught 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 Cypress uncaught exception scenarios; it doesn’t handle the exception 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, “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 must handle different 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. 

You can modify the code to handle the exception for a specific scenario in such cases.

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 so that if the web page returns any state code other than 200, 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

Key Takeaways

  • Errors are prevalent in web applications, which might also occur due to browser compatibility.
  • Since a webpage renders differently on different browser versions, 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 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 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 many devices can be done quickly by leveraging Test Automation frameworks like Cypress and parallel testing for accelerated test cycles.

Run Cypress Tests

Tags
Automated UI Testing Automation Frameworks Automation Testing Cypress

Featured Articles

How to handle Click Events in Cypress

Cypress Best Practices for Test Automation

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.