fix(tests): align redirect destination /auth in route guards tests#117
Conversation
…ctedRoute redirect Bug #3 do plano 10/10. O job CI "Test Coverage" (vitest run --coverage) falhava em main com 1 test failing em 1845 total. Causa-raiz: ProtectedRoute.tsx:37 redireciona para /auth (canonico em prod): if (!user) return <Navigate to="/auth" .../>; Mas os testes admin/reduced-app-navigation.test.tsx e admin/route-no-error-element.test.tsx configuravam: <Route path="/login" element={<LoginStub />} /> Logo o redirect cai num path sem element matching → renderiza vazio → screen.getByTestId("page-login") falha com: Unable to find an element by: [data-testid="page-login"] <body><div /></body> Em produção src/routes/public-routes.tsx mantem AMBAS as rotas: <Route path="/auth" element={<Auth />} /> <Route path="/login" element={<Auth />} /> (alias) Mas TODOS os 3 redirects de guards (ProtectedRoute, AdminRoute, DevRoute) apontam para /auth, que é a rota canonica. /login eh apenas um alias defensivo. Fix cirurgico: mudar path="/login" -> path="/auth" nos 2 testes para alinhar com o destino real do Navigate. Por que nao mudar o redirect para /login no codigo de producao? - Risco alto: OAuth callbacks usam /auth como retorno canonico - 3 arquivos de prod afetados vs 2 de teste Por que nao adicionar AMBAS as rotas no teste? - Mais verbose; o teste deve refletir a realidade da prod - /login alias soh existe pra defensive coding em prod, nao deveria interessar pra um teste de redirect Validacao em lab (clone fresco do main + npm ci + node v22): Antes: tests/admin/route-no-error-element.test.tsx > "anônimo em rota protegida → /login — árvore limpa" -> FAIL (5s timeout em getByTestId) Depois: tests/admin/reduced-app-navigation.test.tsx (6 tests) ✅ tests/admin/route-no-error-element.test.tsx (7 tests) ✅ Subset broader: 314/314 tests passing em 21 files (admin/ + contracts/ + cloud-status + price-freshness) Em produção: zero mudancas. Apenas testes alinhados com Navigate. Roadmap "10/10": ✅ Bug #1 Migrations sync guard (PR #111, 5f3ec9d) ✅ Bug #2 Edge Deno typecheck (PR #115, 0c650ca) 🟢 Bug #3 Test Coverage (este PR) 🟡 Bug #4 ESLint baseline gate (proximo - refinado: nao eh "Run tests" como pensavamos, eh ESLint regression)
Parte 2/2 do Bug #3 do plano 10/10 (mesmo PR). Mesma causa-raiz que reduced-app-navigation.test.tsx: o teste configurava <Route path="/login" element={<LoginStub />} /> mas o ProtectedRoute.tsx:37 redireciona para /auth. Test afetado: "anônimo em rota protegida → /login — árvore limpa" (linha 317) Antes: getByTestId("page-login") timeout 5s (body vazio porque /auth não tinha route matching no MemoryRouter do test) Depois: ✅ 7/7 tests passing Diff: 1 linha (path="/login" → path="/auth").
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
WalkthroughDois arquivos de teste de roteamento foram atualizados para servir o stub de login no caminho ChangesConsolidação de caminho de rota de login em fixtures de teste
Estimated code review effort🎯 1 (Trivial) | ⏱️ ~2 minutos Suggested labels
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Pull request overview
This PR fixes a CI vitest run --coverage failure by aligning the route-guard test harnesses with the production redirect behavior: unauthenticated users are redirected to the canonical /auth route (not /login).
Changes:
- Update the public route registered in two admin test harnesses from
path="/login"topath="/auth". - Keep the same
LoginStubassertions (data-testid="page-login") while ensuring theNavigate to="/auth"redirect actually matches a route inMemoryRouter.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| tests/admin/route-no-error-element.test.tsx | Registers /auth in the ReducedApp router so ProtectedRoute redirects render the login stub instead of an unmatched route. |
| tests/admin/reduced-app-navigation.test.tsx | Registers /auth in the ReducedApp router to match the production guard redirect destination and prevent empty renders in navigation tests. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
…soleto) Após merge do PR #124, PR #125 original ficou dirty com múltiplos conflitos. Cherry-pick apenas dos 4 arquivos cujo valor sobrevive ao merge do #124, descartando o restante (que ou era redundante ou era REVERSÃO de #117/#118/#124). Arquivos aplicados: 1. AppLogo.visual.test.tsx — sidebar variant: h-9 w-9 → h-10 w-10 2. QuoteBuilderDiscountAdvanced.test.tsx — CurrencyInput usa testid (não placeholder) 3. AuthBranding.test.tsx — ContinuousRockets foi inlinado em SpaceScene 4. AuthBranding.visual.test.tsx — Layout atualizado (rounded-3xl px-5 h-[88px]) Arquivos DESCARTADOS do PR #125 original: - tests/admin/reduced-app-navigation + route-no-error-element: reverteriam #117 - tests/components/quotes/AIRecommendationsPanel: reverteria #118 - docs/AUDITORIA + POP secrets + AdminStandardRules + ScenarioSimulation: Tudo já mergeado via #124 - useCatalogState.unit: #124 já skipou explicitamente com TODO de refactor Sanity checks confirmados: - SpaceScene existe em src/pages/auth/AuthBranding.tsx - testid 'quote-discount-input' existe em QuoteBuilderSummaryColumn.tsx:342 - 'h-10 w-10' está em src/components/layout/AppLogo.tsx:29 (sidebar variant)
…soleto) (#130) Após merge do PR #124, PR #125 original ficou dirty com múltiplos conflitos. Cherry-pick apenas dos 4 arquivos cujo valor sobrevive ao merge do #124, descartando o restante (que ou era redundante ou era REVERSÃO de #117/#118/#124). Arquivos aplicados: 1. AppLogo.visual.test.tsx — sidebar variant: h-9 w-9 → h-10 w-10 2. QuoteBuilderDiscountAdvanced.test.tsx — CurrencyInput usa testid (não placeholder) 3. AuthBranding.test.tsx — ContinuousRockets foi inlinado em SpaceScene 4. AuthBranding.visual.test.tsx — Layout atualizado (rounded-3xl px-5 h-[88px]) Arquivos DESCARTADOS do PR #125 original: - tests/admin/reduced-app-navigation + route-no-error-element: reverteriam #117 - tests/components/quotes/AIRecommendationsPanel: reverteria #118 - docs/AUDITORIA + POP secrets + AdminStandardRules + ScenarioSimulation: Tudo já mergeado via #124 - useCatalogState.unit: #124 já skipou explicitamente com TODO de refactor Sanity checks confirmados: - SpaceScene existe em src/pages/auth/AuthBranding.tsx - testid 'quote-discount-input' existe em QuoteBuilderSummaryColumn.tsx:342 - 'h-10 w-10' está em src/components/layout/AppLogo.tsx:29 (sidebar variant)
…#127 Documenta análise + decisão para cada um dos 3 PRs em conflito após #124: - #125: fechado, branch chore/pr125-cherry-pick com 4 testes únicos - #126: fechado, branch chore/pr126-cherry-pick com 2 CORS + 1 auditoria - #127: DRAFT mantido (precisa sessão dedicada com npm install + typecheck) Inclui: - Análise arquivo-por-arquivo de cada PR - Identificação de redundâncias vs main e reversões de #117/#118 - Plano de retomada do #127 (3-5h estimadas) - Lições aprendidas para sessões futuras - Limitação descoberta: MCP do GitHub não expõe github_create_pull_request
…soleto) Após merge do PR #124, PR #125 original ficou dirty com múltiplos conflitos. Cherry-pick apenas dos 4 arquivos cujo valor sobrevive ao merge do #124, descartando o restante (que ou era redundante ou era REVERSÃO de #117/#118/#124). Arquivos aplicados: 1. AppLogo.visual.test.tsx — sidebar variant: h-9 w-9 → h-10 w-10 2. QuoteBuilderDiscountAdvanced.test.tsx — CurrencyInput usa testid (não placeholder) 3. AuthBranding.test.tsx — ContinuousRockets foi inlinado em SpaceScene 4. AuthBranding.visual.test.tsx — Layout atualizado (rounded-3xl px-5 h-[88px]) Arquivos DESCARTADOS do PR #125 original: - tests/admin/reduced-app-navigation + route-no-error-element: reverteriam #117 - tests/components/quotes/AIRecommendationsPanel: reverteria #118 - docs/AUDITORIA + POP secrets + AdminStandardRules + ScenarioSimulation: Tudo já mergeado via #124 - useCatalogState.unit: #124 já skipou explicitamente com TODO de refactor Sanity checks confirmados: - SpaceScene existe em src/pages/auth/AuthBranding.tsx - testid 'quote-discount-input' existe em QuoteBuilderSummaryColumn.tsx:342 - 'h-10 w-10' está em src/components/layout/AppLogo.tsx:29 (sidebar variant)
…soleto) (#134) Após merge do PR #124, PR #125 original ficou dirty com múltiplos conflitos. Cherry-pick apenas dos 4 arquivos cujo valor sobrevive ao merge do #124, descartando o restante (que ou era redundante ou era REVERSÃO de #117/#118/#124). Arquivos aplicados: 1. AppLogo.visual.test.tsx — sidebar variant: h-9 w-9 → h-10 w-10 2. QuoteBuilderDiscountAdvanced.test.tsx — CurrencyInput usa testid (não placeholder) 3. AuthBranding.test.tsx — ContinuousRockets foi inlinado em SpaceScene 4. AuthBranding.visual.test.tsx — Layout atualizado (rounded-3xl px-5 h-[88px]) Arquivos DESCARTADOS do PR #125 original: - tests/admin/reduced-app-navigation + route-no-error-element: reverteriam #117 - tests/components/quotes/AIRecommendationsPanel: reverteria #118 - docs/AUDITORIA + POP secrets + AdminStandardRules + ScenarioSimulation: Tudo já mergeado via #124 - useCatalogState.unit: #124 já skipou explicitamente com TODO de refactor Sanity checks confirmados: - SpaceScene existe em src/pages/auth/AuthBranding.tsx - testid 'quote-discount-input' existe em QuoteBuilderSummaryColumn.tsx:342 - 'h-10 w-10' está em src/components/layout/AppLogo.tsx:29 (sidebar variant)
🐛 Bug #3 do plano "10/10"
Job CI
Test Coverage(vitest run --coverage) falha em main desde 2026-05-22. No último run (1fa53507), step "Run tests with coverage" rodou 7 min antes de quebrar — não é threshold (thresholds zerados na cmdline), é 1 teste falhando em 1845 total.🔍 Causa-raiz
src/components/layout/ProtectedRoute.tsx:37redireciona usuário anônimo para/auth:Mas dois testes configuravam apenas a rota
/loginnoMemoryRouter:Resultado: o
Navigate to="/auth"não tem element matching → renderiza vazio →screen.getByTestId("page-login")falha:Tests afetados (2 arquivos, 2 testes):
tests/admin/reduced-app-navigation.test.tsx:236—"usuário sem sessão em rota protegida → redirect /login sem warning"tests/admin/route-no-error-element.test.tsx:324—"anônimo em rota protegida → /login — árvore limpa"✅ Fix (2 arquivos, +2/-2 linhas — diff cirúrgico)
Mudar
path="/login"→path="/auth"nos dois testes para alinhar com a realidade da produção:O
LoginStubcontinua renderizando<div data-testid="page-login">— apenas o path do matching mudou. Toda a expectativagetByTestId("page-login")permanece igual.🤔 Por que essa estratégia (e não outras)?
Considerei 3 abordagens:
path="/login"→path="/auth"nos 2 tests/logine/authrotas no testProtectedRoute(+AdminRoute,DevRoute) de/auth→/loginEm produção (
src/routes/public-routes.tsx), AMBAS as rotas existem:Mas TODOS os 3 redirects de guards (
ProtectedRoute,AdminRoute,DevRoute) apontam para/auth, que é a rota canônica./loginé apenas alias defensive coding.🧪 Validação em lab (clone fresco do main + Node v22 + npm ci)
tests/admin/route-no-error-element.test.tsxisoladotests/admin/reduced-app-navigation.test.tsxisoladotests/admin/+tests/contracts/+ cloud-status + price-freshness): 21 files🛣️ Roadmap "10/10"
5f3ec9d)keyof S & stringin parseContract to fix TS2345 in 15 edge functions #115 (0c650ca)Lint, Typecheck & Testfalha no step "ESLint baseline gate" ANTES do "Run tests" (que fica skipped). Próximo PR.📜 Decision trail
keyof S & stringin parseContract to fix TS2345 in 15 edge functions #115 → fix(contracts): infer V from versions keys to unblock Edge Deno typecheck #116): listei 6 PRs abertos antes de criar branch; nenhum ataca Bug chore: remover 6 scripts refactor_imports*.cjs lixo (origem dos 32 imports quebrados) #3🤖 Pink e Cerébro proceeding.
Summary by cubic
Align route-guard tests to use /auth instead of /login, matching the
ProtectedRouteredirect and fixing the failing coverage job. No production code changed./authredirect soNavigatehas a matching element: tests/admin/reduced-app-navigation.test.tsx, tests/admin/route-no-error-element.test.tsx.Written for commit 830a6b3. Summary will update on new commits. Review in cubic
Summary by CodeRabbit
Release Notes
/auth(anteriormente/login). Ajustes implementados nos testes de navegação para garantir cobertura adequada da estrutura de rotas protegidas.