In Cypress, a request timeout typically occurs when waiting for a server response to an HTTP request exceeds the predefined time. To handle this type of error, you can use Cypress's .request() command and leverage its timeout option. When a request times out, Cypress throws an error, which you can catch using .catch().
Here is an example demonstrating how to capture request timeout errors in Cypress tests:
javascript// Example: Send an API request with a 500ms timeout cy.request({ url: 'http://yourapi.com/data', method: 'GET', timeout: 500 // Set request timeout to 500 milliseconds }).then((response) => { // Request successful, handle response data console.log('Request successful:', response); }).catch((error) => { // Request failed, catch error information if (error.name === 'TimeoutError') { // If it's a timeout error, handle it specifically console.error('Captured request timeout error:', error); } else { // Handle other error types console.error('Captured other request errors:', error); } });
In this example, we configure a request with a 500-millisecond timeout. If the request does not receive a response within this window, the cy.request command fails, and the error object is caught by .catch(). Within the .catch() block, we inspect the name property of the error object to identify if it is a TimeoutError, enabling us to implement tailored handling logic for different error types.
It's important to note that Cypress commands typically automatically retry until a timeout occurs. Therefore, in practical test scripts, manual error catching for timeouts is generally unnecessary unless you require specific error handling. Typically, you only need to set an appropriate timeout duration so that Cypress automatically marks the test as failed when a timeout occurs.