How to Fix Timeout Error in Cypress Tests Quickly
A
timeout error in Cypress happens when a command takes longer than the default wait time (usually 4 seconds). To fix it, increase the timeout using { timeout: value } on commands or globally in cypress.config.js, or improve your app's response time to avoid delays.Why This Happens
Cypress commands wait for elements or responses up to a default timeout (4 seconds). If the element does not appear or an action does not complete in time, Cypress throws a timeout error. This often happens when the page loads slowly, network requests take longer, or selectors are incorrect.
javascript
describe('Timeout example', () => { it('fails due to timeout', () => { cy.visit('https://example.com') cy.get('#slow-element').click() // Element appears after 6 seconds }) })
Output
Timed out retrying: Expected to find element: '#slow-element', but never found it.
The Fix
Increase the timeout for the command that waits for the slow element. You can add { timeout: 10000 } to wait up to 10 seconds. Alternatively, set a global timeout in cypress.config.js to cover all commands.
javascript
describe('Timeout fixed example', () => { it('waits longer for slow element', () => { cy.visit('https://example.com') cy.get('#slow-element', { timeout: 10000 }).click() // Waits up to 10 seconds }) })
Output
Test passes if '#slow-element' appears within 10 seconds and is clicked.
Prevention
To avoid timeout errors, use these best practices:
- Use reliable selectors that match elements quickly.
- Increase timeouts only when necessary, not by default.
- Use
cy.intercept()to wait for network calls explicitly. - Optimize your app to load elements faster.
- Set global timeouts in
cypress.config.jsfor consistent waits.
Related Errors
Other common Cypress errors related to timeouts include:
- "Timed out retrying: Expected to find element but never found it" - caused by wrong selectors or slow loading.
- "Request timed out" - network requests taking too long; fix by increasing
timeoutincy.intercept(). - "Command failed because element is detached from the DOM" - element changed during wait; fix by using stable selectors or waiting for network calls.
Key Takeaways
Timeout errors happen when Cypress waits longer than default for elements or responses.
Fix timeout errors by increasing command or global timeouts with the { timeout: value } option.
Use reliable selectors and wait for network calls explicitly to prevent timeouts.
Optimize your app's loading speed to reduce Cypress waiting times.
Set global timeouts in cypress.config.js for consistent test behavior.