Effective error handling is a fundamental component of building reliable and maintainable automated tests. In Cypress, managing errors and exceptions ensures tests run smoothly and provide meaningful results.
In Cypress, errors can originate from the webpage under test, issues in the test script, or unexpected application behavior. If not handled properly, these errors can cause tests to fail prematurely and make debugging more difficult.
This article explores different strategies for handling errors in Cypress, focusing on scenarios such as unexpected status codes, test failures, and exceptions from the application under test.
Understanding Error Handling in Cypress
An Exception or Error is an abnormal event that may break the normal flow of test script execution, causing the tests to fail. In Cypress, exceptions may originate from the Application/web Page Under Test or your automation script.
Error handling in Cypress refers to managing errors that occur during test execution. These errors can stem from the application under test, network failures, or issues within the test script itself. Error handling ensures tests don’t fail unexpectedly and provides clearer insights into issues.
Effective error handling offers multiple benefits, including:
- Improved Test Stability: Reduces false failures caused by transient issues, such as timing or network delays.
- Clearer Debugging: Provides actionable error messages, making it easier to identify and resolve issues.
- Consistent Test Execution: Ensures tests run reliably even when unexpected errors occur in the application or network.
- Better Reporting: Offers more detailed context in test failures, aiding in quicker root-cause analysis.
- Enhanced Efficiency: Allows tests to continue running after errors are handled, reducing test interruption and saving time.
- Increased Test Coverage: Helps ensure that more scenarios are tested, even in the presence of errors.
By leveraging platforms like BrowserStack, you can extend Cypress’s capabilities by executing your tests on a variety of real browsers and devices in the cloud.
This helps ensure consistent error handling across different environments and provides a comprehensive view of your application’s behavior under diverse conditions, such as different browsers and operating systems.
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:
- Handling Exception from Webpage Under Test in Cypress
- Handling Exceptions within the Code in Cypress
- Validate Specific Exceptions
- Handling Failure Exception in Cypress
- Handing Exception due to Unexpected Status Code in Cypress
Here is a detailed breakdown of each type 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.
Read More: Cross-Browser Testing with Cypress: Tutorial
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.”
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');
})
})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.
Read More: How to debug Cypress Tests: Tutorial
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')
})
})To 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 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')
})
})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})
})
})Conclusion
Errors are common in web applications, and many arise due to browser compatibility. Since webpages render differently across various browsers and browser versions, it’s essential to test compatibility across multiple operating systems. These compatibility errors are typically identified during cross-browser testing.
Setting up the necessary infrastructure for cross-platform testing can be time-consuming and expensive. However, with a real device cloud like BrowserStack, testers gain access to over 3500+ real devices and browsers, ensuring comprehensive test coverage under actual user conditions.
This approach simplifies the testing process, reduces costs, and guarantees that applications perform reliably across different environments.








