1- # Timeout Diagnostics - Smart Error Messages
1+ # Timeout Diagnostics – Smart Error Messages
22
3- ## 🎯 Objetivo
3+ ## 🎯 Objective
44
5- Melhorar dramaticamente a experiência do desenvolvedor ao lidar com erros de timeout no Cypress, fornecendo ** sugestões contextuais e acionáveis ** baseadas na análise do contexto do erro .
5+ Deliver a dramatically better developer experience when Cypress commands time out by providing ** contextual, actionable suggestions ** derived from the error context .
66
7- ## 🚀 Motivação
7+ ## 🚀 Motivation
88
9- Erros de timeout são extremamente comuns em testes Cypress, mas as mensagens tradicionais são genéricas :
9+ Timeout errors are extremely common in Cypress tests, yet the built-in messages are typically generic :
1010
1111```
1212cy.get() timed out waiting 4000ms
1313```
1414
15- Com este sistema, os desenvolvedores recebem diagnósticos inteligentes :
15+ With Timeout Diagnostics, developers receive intelligent hints that explain likely causes and quick fixes :
1616
1717```
1818cy.get() timed out waiting 4000ms
@@ -21,58 +21,58 @@ cy.get() timed out waiting 4000ms
2121
22221. The selector appears to target dynamic/loading content
2323 a) Wait for the loading state to complete: cy.get('.loading-spinner').should('not.exist')
24- b) Consider using data-cy attributes instead of class names that indicate loading states
24+ b) Prefer stable data-cy attributes instead of CSS classes that indicate loading states
2525 c) Use cy.intercept() to wait for the API request that populates this content
2626 📚 Learn more: https://on.cypress.io/best-practices#Selecting-Elements
2727
28282. 8 network requests are still pending
2929 a) Wait for specific API calls to complete using cy.intercept()
3030 b) Consider increasing the timeout if the requests are expected to be slow
31- c) Check if some requests are failing or hanging in the Network tab
32- d) Example: cy.intercept(" GET", " /api/data" ).as(" getData" ); cy.wait(" @getData" )
31+ c) Check the Network tab for requests that are failing or hanging
32+ d) Example: cy.intercept(' GET', ' /api/data' ).as(' getData' ); cy.wait(' @getData' )
3333 📚 Learn more: https://on.cypress.io/intercept
3434```
3535
36- ## ✨ Funcionalidades
36+ ## ✨ Feature Highlights
3737
38- ### 1. ** Detecção de Seletores Problemáticos **
39- - Identifica seletores que apontam para conteúdo dinâmico (loading, spinner, skeleton )
40- - Detecta seletores complexos e frágeis
41- - Alerta sobre IDs dinâmicos (ex: ` #user-12345 ` )
38+ ### 1. ** Problematic Selector Detection **
39+ - Detects selectors that target dynamic content (spinners, skeletons, loading states )
40+ - Flags complex or fragile selectors
41+ - Warns when IDs look dynamically generated (e.g., ` #user-12345 ` )
4242
43- ### 2. ** Análise de Problemas de Rede **
44- - Detecta múltiplas requisições pendentes
45- - Identifica timeouts longos que sugerem operações assíncronas
46- - Sugere uso de ` cy.intercept() ` para melhor controle
43+ ### 2. ** Network Issue Analysis **
44+ - Surfaces pending requests
45+ - Flags unusually long timeouts that suggest async operations still running
46+ - Promotes ` cy.intercept() ` and explicit waits for stability
4747
48- ### 3. ** Diagnóstico de Animações **
49- - Identifica quando animações estão causando delays
50- - Sugere configurações para desabilitar animações em testes
48+ ### 3. ** Animation Diagnostics **
49+ - Identifies when animations delay actionability
50+ - Suggests disabling animations per test or globally
5151
52- ### 4. ** Detecção de Mutações Excessivas do DOM **
53- - Identifica quando o DOM está mudando rapidamente
54- - Sugere esperar por estabilização antes de interagir
52+ ### 4. ** DOM Mutation Detection **
53+ - Spots rapidly changing DOMs
54+ - Recommends waiting for stability before interacting
5555
56- ### 5. ** Sugestões Específicas por Comando **
57- - Sugestões customizadas para cada tipo de comando ( ` get ` , ` click ` , ` type ` , etc.)
58- - Links para documentação relevante
56+ ### 5. ** Command-Specific Tips **
57+ - Tailored suggestions for ` cy. get` , ` cy. click` , ` cy. type` , etc.
58+ - Links to the relevant Cypress docs for deeper guidance
5959
60- ## 📦 Estrutura
60+ ## 📦 Project Structure
6161
6262```
6363packages/driver/src/cypress/
64- └── timeout_diagnostics.ts # Lógica principal
64+ └── timeout_diagnostics.ts # Core analysis + formatting logic
6565
6666packages/driver/test/unit/cypress/
67- └── timeout_diagnostics.spec.ts # Testes unitários
67+ └── timeout_diagnostics.spec.ts # Unit tests
6868```
6969
70- ## 🔧 API
70+ ## 🔧 API Overview
7171
7272``` typescript
7373import { TimeoutDiagnostics } from ' ./timeout_diagnostics'
7474
75- // Analisar contexto e obter sugestões
75+ // Analyze the context and get suggestions
7676const suggestions = TimeoutDiagnostics .analyze ({
7777 command: ' get' ,
7878 selector: ' .loading-spinner' ,
@@ -81,60 +81,60 @@ const suggestions = TimeoutDiagnostics.analyze({
8181 animationsRunning: true ,
8282})
8383
84- // Formatar sugestões para exibição
84+ // Format the output for display
8585const formatted = TimeoutDiagnostics .formatSuggestions (suggestions )
8686
87- // Enriquecer mensagem de erro existente
87+ // Enhance an existing error message with diagnostics
8888const enhanced = TimeoutDiagnostics .enhanceTimeoutError (
8989 ' cy.get() timed out' ,
90- context
90+ context ,
9191)
9292```
9393
94- ## 🎨 Exemplos de Uso
94+ ## 🎨 Usage Examples
9595
96- ### Exemplo 1: Conteúdo Dinâmico
96+ ### Example 1: Dynamic Content
9797``` typescript
98- // Teste que falha
98+ // Failing test
9999cy .get (' .loading-spinner' ).click ()
100100
101- // Erro melhorado sugere :
102- // "Wait for the loading state to complete:
101+ // Enhanced error suggests :
102+ // "Wait for the loading state to complete:
103103// cy.get('.loading-spinner').should('not.exist')"
104104```
105105
106- ### Exemplo 2: Problemas de Rede
106+ ### Example 2: Network Issues
107107``` typescript
108- // Teste aguardando resposta API
108+ // Test waiting on API data
109109cy .get (' .user-data' ).should (' be.visible' )
110110
111- // Erro melhorado sugere :
111+ // Enhanced error suggests :
112112// "Use cy.intercept() to wait for the specific request:
113113// cy.intercept('GET', '/api/users').as('getUsers')
114114// cy.wait('@getUsers')"
115115```
116116
117- ### Exemplo 3: Animações
117+ ### Example 3: Animations
118118``` typescript
119- // Elemento animando quando clica
119+ // Element is mid-animation when clicked
120120cy .get (' .modal-button' ).click ()
121121
122- // Erro melhorado sugere :
122+ // Enhanced error suggests :
123123// "Disable animations: .click({ waitForAnimations: false })
124124// Or globally: Cypress.config('animationDistanceThreshold', 0)"
125125```
126126
127- ## 🔮 Integração Futura
127+ ## 🔮 Future Integration
128128
129- Para integrar completamente no Cypress, seria necessário :
129+ To fully integrate with Cypress core we would need to :
130130
131- 1 . ** Modificar ` error_utils.ts ` ** para capturar contexto adicional durante timeouts
132- 2 . ** Coletar métricas ** de rede , DOM e animações durante execução do comando
133- 3 . ** Integrar na pipeline de erro ** existente do Cypress
134- 4 . ** Adicionar configuração ** para habilitar/desabilitar diagnósticos
131+ 1 . ** Extend ` error_utils.ts ` ** to capture richer context when timeouts occur.
132+ 2 . ** Collect runtime metrics ** (network , DOM mutations, animations) alongside each command.
133+ 3 . ** Pipe diagnostics into the existing error formatter ** so suggestions appear automatically.
134+ 4 . ** Add configuration flags ** so users can opt in/out or tweak verbosity.
135135
136136``` typescript
137- // Exemplo de integração em error_utils.ts
137+ // Sketch for error_utils.ts
138138import TimeoutDiagnostics from ' ./timeout_diagnostics'
139139
140140const createTimeoutError = (cmd , ms ) => {
@@ -146,53 +146,52 @@ const createTimeoutError = (cmd, ms) => {
146146 animationsRunning: hasRunningAnimations (),
147147 domMutations: getDOMMutationCount (),
148148 }
149-
149+
150150 const baseMessage = ` cy.${cmd .get (' name' )}() timed out waiting ${ms }ms `
151151 return TimeoutDiagnostics .enhanceTimeoutError (baseMessage , context )
152152}
153153```
154154
155- ## 📊 Benefícios
155+ ## 📊 Benefits
156156
157- 1 . ** Reduz tempo de debugging** : Desenvolvedores identificam problemas mais rapidamente
158- 2 . ** Educação inline ** : Ensina melhores práticas durante o desenvolvimento
159- 3 . ** Menos frustração ** : Erros mais claros = desenvolvedores mais felizes
160- 4 . ** Reduz issues no GitHub** : Menos perguntas sobre "por que meu teste timeout?"
161- 5 . ** Melhora adoção ** : Desenvolvedores iniciantes aprendem mais rápido
157+ 1 . ** Faster debugging** – developers quickly learn which condition to address.
158+ 2 . ** Inline education ** – suggests Cypress best practices in the moment.
159+ 3 . ** Lower frustration ** – clearer errors mean happier engineers.
160+ 4 . ** Fewer GitHub issues ** – reduces "why is my test timing out?" questions.
161+ 5 . ** Easier onboarding ** – newer users learn patterns through the suggestions.
162162
163- ## 🧪 Testes
163+ ## 🧪 Tests
164164
165- Execute os testes unitários :
165+ Run the unit suite :
166166
167167``` bash
168168cd packages/driver
169169yarn test timeout_diagnostics.spec.ts
170170```
171171
172- Cobertura inclui:
173- - ✅ Detecção de todos os tipos de problemas
174- - ✅ Formatação de mensagens
175- - ✅ Casos extremos e edge cases
176- - ✅ Combinação de múltiplos diagnósticos
172+ Coverage includes:
173+ - ✅ Selector, network, animation, and DOM mutation detection
174+ - ✅ Message formatting
175+ - ✅ Edge cases and combined diagnostics
177176
178- ## 🚀 Próximos Passos
177+ ## 🚀 Next Steps
179178
180- 1 . ✅ Criar módulo de diagnósticos com testes
181- 2 . ⏳ Integrar com sistema de erros existente
182- 3 . ⏳ Adicionar coleta de métricas de contexto
183- 4 . ⏳ Criar configuração para habilitar/desabilitar
184- 5 . ⏳ Adicionar mais padrões e sugestões baseado em feedback
185- 6 . ⏳ Documentação para usuários finais
179+ 1 . ✅ Build the diagnostics module with tests
180+ 2 . ⏳ Wire it into the existing error system
181+ 3 . ⏳ Capture contextual metrics during command execution
182+ 4 . ⏳ Provide configuration toggles for diagnostics
183+ 5 . ⏳ Expand heuristics based on user feedback
184+ 6 . ⏳ Document the feature for end users
186185
187- ## 🤝 Contribuindo
186+ ## 🤝 Contributing
188187
189- Este é um sistema extensível. Para adicionar novos diagnósticos :
188+ Timeout Diagnostics is intentionally extensible. To add new heuristics :
190189
191- 1 . Adicione padrão em ` COMMON_PATTERNS `
192- 2 . Crie método ` analyze*Issues() `
193- 3 . Adicione testes correspondentes
194- 4 . Documente o novo diagnóstico
190+ 1 . Add a pattern to ` COMMON_PATTERNS ` .
191+ 2 . Implement a corresponding ` analyze*Issues() ` helper.
192+ 3 . Cover it with unit tests.
193+ 4 . Document the behavior in this README.
195194
196- ## 📝 Licença
195+ ## 📝 License
197196
198- MIT - Consistente com o projeto Cypress
197+ MIT — consistent with the Cypress project.
0 commit comments