Skip to content

fix(tests): align redirect destination /auth in route guards tests#117

Merged
adm01-debug merged 2 commits into
mainfrom
fix/test-coverage-route-auth-redirect
May 23, 2026
Merged

fix(tests): align redirect destination /auth in route guards tests#117
adm01-debug merged 2 commits into
mainfrom
fix/test-coverage-route-auth-redirect

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

@adm01-debug adm01-debug commented May 22, 2026

🐛 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:37 redireciona usuário anônimo para /auth:

if (!user) {
  savePostLoginRedirect(...);
  return <Navigate to="/auth" state={{ from: location }} replace />;
}

Mas dois testes configuravam apenas a rota /login no MemoryRouter:

<Routes>
  <Route path="/login" element={<LoginStub />} />  // ← rota errada
  <Route element={<ProtectedRoute />}>
    ...
  </Route>
</Routes>

Resultado: o Navigate to="/auth" não tem element matching → renderiza vazio → screen.getByTestId("page-login") falha:

TestingLibraryElementError: Unable to find an element by: [data-testid="page-login"]
<body><div /></body>

at tests/admin/route-no-error-element.test.tsx:324:12

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:

-          <Route path="/login" element={<LoginStub />} />
+          <Route path="/auth" element={<LoginStub />} />

O LoginStub continua renderizando <div data-testid="page-login"> — apenas o path do matching mudou. Toda a expectativa getByTestId("page-login") permanece igual.

🤔 Por que essa estratégia (e não outras)?

Considerei 3 abordagens:

Mudança Arquivos Risco
A (escolhida) path="/login"path="/auth" nos 2 tests 2 testes (1 linha cada) Mínimo — alinha test com prod
B Adicionar BOTH /login e /auth rotas no test 2 testes (+1 linha cada) Baixo, mas verboso
C Mudar ProtectedRoute (+ AdminRoute, DevRoute) de /auth/login 3 arquivos PROD Alto — pode quebrar OAuth callback flow

Em produção (src/routes/public-routes.tsx), AMBAS as rotas existem:

<Route path="/auth" element={<Auth />} />
<Route path="/login" element={<Auth />} />  {/* alias defensivo */}

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)

Validação Antes Depois
tests/admin/route-no-error-element.test.tsx isolado ❌ FAIL (1/7) 7/7
tests/admin/reduced-app-navigation.test.tsx isolado ❌ FAIL (1/6) 6/6
Subset (tests/admin/ + tests/contracts/ + cloud-status + price-freshness): 21 files n/a 314/314
Em produção ZERO mudanças (só testes)

🛣️ Roadmap "10/10"

📜 Decision trail

🤖 Pink e Cerébro proceeding.


Summary by cubic

Align route-guard tests to use /auth instead of /login, matching the ProtectedRoute redirect and fixing the failing coverage job. No production code changed.

  • Bug Fixes
    • Updated test routes to match the /auth redirect so Navigate has 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

  • Tests
    • Atualizados testes de roteamento para refletir a rota de autenticação em /auth (anteriormente /login). Ajustes implementados nos testes de navegação para garantir cobertura adequada da estrutura de rotas protegidas.

Review Change Stack

…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").
Copilot AI review requested due to automatic review settings May 22, 2026 23:07
@vercel
Copy link
Copy Markdown

vercel Bot commented May 22, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
we-dream-big Ready Ready Preview, Comment May 22, 2026 11:07pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 22, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2e47819f-c0d3-4e1a-9d0c-eee104506886

📥 Commits

Reviewing files that changed from the base of the PR and between 1cb3b47 and 830a6b3.

📒 Files selected for processing (2)
  • tests/admin/reduced-app-navigation.test.tsx
  • tests/admin/route-no-error-element.test.tsx

Walkthrough

Dois arquivos de teste de roteamento foram atualizados para servir o stub de login no caminho /auth em vez de /login. As estruturas de rotas reduzidas usadas nas suites de integração agora refletem esse consolidação de caminho de autenticação.

Changes

Consolidação de caminho de rota de login em fixtures de teste

Layer / File(s) Resumo
Consolidação de path de login em fixtures
tests/admin/reduced-app-navigation.test.tsx, tests/admin/route-no-error-element.test.tsx
Rotas de stub de login foram alteradas de path="/login" para path="/auth" em ambas as suites de integração de roteamento reduzido.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~2 minutos

Suggested labels

javascript

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed O título descreve com precisão a mudança principal: alinhamento do destino de redirecionamento para /auth nos testes de route guards.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/test-coverage-route-auth-redirect

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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" to path="/auth".
  • Keep the same LoginStub assertions (data-testid="page-login") while ensuring the Navigate to="/auth" redirect actually matches a route in MemoryRouter.

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.

Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 2 files

Re-trigger cubic

@supabase
Copy link
Copy Markdown

supabase Bot commented May 22, 2026

This pull request has been ignored for the connected project doufsxqlfjyuvxuezpln because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@adm01-debug adm01-debug merged commit 8e24d8a into main May 23, 2026
29 of 32 checks passed
@adm01-debug adm01-debug deleted the fix/test-coverage-route-auth-redirect branch May 23, 2026 10:56
adm01-debug added a commit that referenced this pull request May 23, 2026
…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)
adm01-debug added a commit that referenced this pull request May 23, 2026
…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)
adm01-debug added a commit that referenced this pull request May 23, 2026
…#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
adm01-debug added a commit that referenced this pull request May 23, 2026
…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)
adm01-debug added a commit that referenced this pull request May 23, 2026
…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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants