Skip to content

Commit ba27030

Browse files
docs(driver): translate remaining README sections to English
1 parent 31df04b commit ba27030

File tree

1 file changed

+118
-169
lines changed

1 file changed

+118
-169
lines changed
Lines changed: 118 additions & 169 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
1-
# Timeout Diagnostics - Smart Error Messages
1+
<!-- NOTE: This file documents a work-in-progress experimental feature. It is NOT integrated into the main Cypress error pipeline yet. -->
2+
# Timeout Diagnostics — Smart Timeout Error Messages (WIP)
23

3-
## 🎯 Objetivo
4+
## Objective
45

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.
6+
Improve the developer experience when dealing with timeout errors in Cypress by providing actionable, context-aware suggestions based on analysis of the failure context.
67

7-
## 🚀 Motivação
8+
## Motivation
89

9-
Erros de timeout são extremamente comuns em testes Cypress, mas as mensagens tradicionais são genéricas:
10+
Timeout errors are extremely common in Cypress tests, yet default messages are often generic and unhelpful:
1011

1112
```
1213
cy.get() timed out waiting 4000ms
1314
```
1415

15-
Com este sistema, os desenvolvedores recebem diagnósticos inteligentes:
16+
This diagnostics system aims to enrich those messages with intelligent, actionable suggestions:
1617

1718
```
1819
cy.get() timed out waiting 4000ms
@@ -27,172 +28,120 @@ cy.get() timed out waiting 4000ms
2728
2829
2. 8 network requests are still pending
2930
a) Wait for specific API calls to complete using cy.intercept()
30-
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")
33-
📚 Learn more: https://on.cypress.io/intercept
34-
```
35-
36-
## ✨ Funcionalidades
37-
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`)
42-
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
47-
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
51-
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
55-
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
59-
60-
## 📦 Estrutura
61-
62-
```
63-
packages/driver/src/cypress/
64-
└── timeout_diagnostics.ts # Lógica principal
65-
66-
packages/driver/test/unit/cypress/
67-
└── timeout_diagnostics.spec.ts # Testes unitários
68-
```
69-
70-
## 🔧 API
71-
72-
```typescript
73-
import { TimeoutDiagnostics } from './timeout_diagnostics'
74-
75-
// Analisar contexto e obter sugestões
76-
const suggestions = TimeoutDiagnostics.analyze({
77-
command: 'get',
78-
selector: '.loading-spinner',
79-
timeout: 4000,
80-
networkRequests: 5,
81-
animationsRunning: true,
82-
})
83-
84-
// Formatar sugestões para exibição
85-
const formatted = TimeoutDiagnostics.formatSuggestions(suggestions)
86-
87-
// Enriquecer mensagem de erro existente
88-
const enhanced = TimeoutDiagnostics.enhanceTimeoutError(
89-
'cy.get() timed out',
90-
context
91-
)
92-
```
93-
94-
## 🎨 Exemplos de Uso
95-
96-
### Exemplo 1: Conteúdo Dinâmico
97-
```typescript
98-
// Teste que falha
99-
cy.get('.loading-spinner').click()
100-
101-
// Erro melhorado sugere:
102-
// "Wait for the loading state to complete:
103-
// cy.get('.loading-spinner').should('not.exist')"
104-
```
105-
106-
### Exemplo 2: Problemas de Rede
107-
```typescript
108-
// Teste aguardando resposta API
109-
cy.get('.user-data').should('be.visible')
110-
111-
// Erro melhorado sugere:
112-
// "Use cy.intercept() to wait for the specific request:
113-
// cy.intercept('GET', '/api/users').as('getUsers')
114-
// cy.wait('@getUsers')"
115-
```
116-
117-
### Exemplo 3: Animações
118-
```typescript
119-
// Elemento animando quando clica
120-
cy.get('.modal-button').click()
121-
122-
// Erro melhorado sugere:
123-
// "Disable animations: .click({ waitForAnimations: false })
124-
// Or globally: Cypress.config('animationDistanceThreshold', 0)"
125-
```
126-
127-
## 🔮 Integração Futura
128-
129-
Para integrar completamente no Cypress, seria necessário:
130-
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
135-
136-
```typescript
137-
// Exemplo de integração em error_utils.ts
138-
import TimeoutDiagnostics from './timeout_diagnostics'
139-
140-
const createTimeoutError = (cmd, ms) => {
141-
const context = {
142-
command: cmd.get('name'),
143-
selector: cmd.get('selector'),
144-
timeout: ms,
145-
networkRequests: getNetworkMonitor().pendingCount(),
146-
animationsRunning: hasRunningAnimations(),
147-
domMutations: getDOMMutationCount(),
31+
<!-- NOTE: This file documents a work-in-progress experimental feature. It is NOT integrated into the main Cypress error pipeline yet. -->
32+
# Timeout Diagnostics — Smart Timeout Error Messages (WIP)
33+
34+
Status: Work‑in‑progress (not yet integrated into Cypress). This document describes an experimental timeout diagnostics system that analyzes command context (selectors, network, animations, DOM mutations) and produces contextual recommendations to help users address flaky or timing-related failures.
35+
36+
Objective
37+
---------
38+
Improve the developer experience for timeout errors by producing actionable, context-aware suggestions when a command times out. Instead of a generic message like `cy.get() timed out waiting 4000ms`, diagnostics should indicate likely causes (dynamic content, pending network requests, animations, etc.) and suggest concrete fixes.
39+
40+
Motivation
41+
----------
42+
Timeouts are a frequent source of confusion in end-to-end tests. The goal of this feature is to reduce debugging time and teach best practices inline by providing targeted suggestions and examples.
43+
44+
Example enhanced output
45+
-----------------------
46+
```
47+
cy.get('.user-list') timed out waiting 4000ms
48+
49+
Diagnostic suggestions:
50+
51+
1) Selector likely targets dynamic content
52+
• Wait for the loading state: cy.get('.loading-spinner').should('not.exist')
53+
• Prefer stable data attributes: e.g. [data-cy="user-list"]
54+
• Consider intercepting the API call that populates this content
55+
56+
2) Network requests pending (8)
57+
• Use cy.intercept('GET', '/api/users').as('getUsers') and cy.wait('@getUsers')
58+
• If requests are expected to be slow, either wait for the specific request or increase the timeout
59+
60+
Learn more: https://on.cypress.io/intercept
61+
```
62+
63+
Features
64+
--------
65+
- Problematic selector detection (loading spinners, skeletons, dynamic IDs)
66+
- Network analysis (pending requests, slow/long-running requests)
67+
- Animation detection and guidance to reduce timing flakiness
68+
- Detection of excessive DOM mutations and recommendations to wait for stability
69+
- Command-specific suggestions (get, click, type, etc.) and doc links
70+
71+
Project structure (implementation sketch)
72+
----------------------------------------
73+
```
74+
packages/driver/src/cypress/
75+
timeout_diagnostics.ts — core analysis + formatting (WIP)
76+
77+
packages/driver/test/unit/cypress/
78+
timeout_diagnostics.spec.ts — unit tests
79+
```
80+
81+
API sketch
82+
----------
83+
```ts
84+
// analyze context and produce suggestions
85+
const suggestions = TimeoutDiagnostics.analyze({
86+
command: 'get',
87+
selector: '.loading-spinner',
88+
timeout: 4000,
89+
networkRequests: 5,
90+
animationsRunning: true,
91+
})
92+
93+
const formatted = TimeoutDiagnostics.formatSuggestions(suggestions)
94+
95+
// enhance base timeout message with suggestions
96+
const enhanced = TimeoutDiagnostics.enhanceTimeoutError('cy.get() timed out', context)
97+
```
98+
99+
Integration notes
100+
-----------------
101+
To integrate this into Cypress's existing error pipeline we would:
102+
103+
1. Extend `error_utils` (or the error creation path) to provide additional context (selector, pending network count, DOM mutation rate, animation state) when creating a timeout error.
104+
2. Call `TimeoutDiagnostics.analyze(context)` and append the returned suggestions to the error message (optionally behind a feature flag).
105+
3. Add a configuration option to opt in/out of diagnostics in CI or local environments.
106+
107+
Integration example (pseudo):
108+
```ts
109+
import TimeoutDiagnostics from './timeout_diagnostics'
110+
111+
function createTimeoutError(cmd, ms) {
112+
const context = {
113+
command: cmd.get('name'),
114+
selector: cmd.get('selector'),
115+
timeout: ms,
116+
networkRequests: getNetworkMonitor().pendingCount(),
117+
animationsRunning: hasRunningAnimations(),
118+
domMutations: getDOMMutationCount(),
119+
}
120+
121+
const baseMessage = `cy.${cmd.get('name')}() timed out waiting ${ms}ms`
122+
return TimeoutDiagnostics.enhanceTimeoutError(baseMessage, context)
148123
}
149-
150-
const baseMessage = `cy.${cmd.get('name')}() timed out waiting ${ms}ms`
151-
return TimeoutDiagnostics.enhanceTimeoutError(baseMessage, context)
152-
}
153-
```
154-
155-
## 📊 Benefícios
156-
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
124+
```
162125

163-
## 🧪 Testes
164-
165-
Execute os testes unitários:
166-
167-
```bash
168-
cd packages/driver
169-
yarn test timeout_diagnostics.spec.ts
170-
```
126+
Tests
127+
-----
128+
Run unit tests for the diagnostics module:
171129

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
130+
```powershell
131+
cd packages/driver
132+
yarn test timeout_diagnostics.spec.ts
133+
```
177134

178-
## 🚀 Próximos Passos
135+
Notes & next steps
136+
------------------
137+
- This README documents the experimental design and examples. The feature is intentionally left out of the main error flow until heuristics and runtime metric collection are reviewed.
138+
- Next: finalize analysis heuristics, expand unit tests, and implement an opt-in integration path in `error_utils`.
179139

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
140+
License
141+
-------
142+
MIT — consistent with the Cypress project
186143

187-
## 🤝 Contribuindo
188-
189-
Este é um sistema extensível. Para adicionar novos diagnósticos:
190-
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
195-
196-
## 📝 Licença
197-
198-
MIT - Consistente com o projeto Cypress
144+
If you'd like, I can also:
145+
- normalize the file encoding/artifacts (there were some garbled characters in the original), and
146+
- open a small PR on the `feat/timeout-diagnostics` branch with this cleaned README.
147+
animationsRunning: hasRunningAnimations(),

0 commit comments

Comments
 (0)