Skip to content

fix(tests): repara 6 testes/componente sobre a main (onda CI-green)#35

Merged
adm01-debug merged 2 commits into
mainfrom
fix/ci-tests-green-onmain
May 22, 2026
Merged

fix(tests): repara 6 testes/componente sobre a main (onda CI-green)#35
adm01-debug merged 2 commits into
mainfrom
fix/ci-tests-green-onmain

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

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

Resumo

Repara 6 arquivos de teste/componente que falhavam na main, re-aplicados sobre a main fresca (não copiados de PRs antigos — a produção da main divergiu desde então).

Fixes (cada um validado com TZ=America/Sao_Paulo, como o CI)

Arquivo Causa-raiz Tipo
quoteService.test.ts mock usava eq().eq().maybeSingle(); produção é eq().single() 1-arg drift de teste
tests/contexts/AuthContext.test.tsx faltava refreshSession no mock auth; thenable .then() chamado sem args (produção usa .then() vazio) drift de teste
BridgeMetricsOverlay.tsx gate só checava isDev; precisa isDev && isAllowed (admin não-dev e dev sem SSOT devem ficar ocultos) bug de segurança
Auth.test.tsx mock @/hooks/admin sem useDevGate; forgot-form monta via AnimatePresence (assíncrono) drift de teste
AdminLayout.test.tsx MainLayout real (lazyWithRetry+Suspense) pendura montado 2x em jsdom; mock supabase incompleto drift de teste
FiltersPage.no-duplicate-sidebar.test.tsx path desatualizado pós-reorg (src/pages/products/) drift de teste

O MainLayout real tem cobertura dedicada em tests/components/layout/MainLayout.breadcrumbs.test.tsx, então mocká-lo aqui não perde cobertura.

Verificação

  • 6 arquivos: 21/21 testes passando (TZ correto).
  • 0 regressão: demais falhas da main são pré-existentes (confirmado rodando-as em working tree limpo, sem estes fixes).

Nota

Não esgota o CI: a main tem ~20 outros arquivos de teste com falhas pré-existentes (herança de merges paralelos), a serem tratados em PRs subsequentes.


Substitui o #27 (que estava sobre base obsoleta db94c9b).


Summary by cubic

Fixes six failing tests on main and updates the dev metrics overlay to require both dev role and gate approval. Adds docs/DECISION-LOG-2026-05-21-v2.md mapping remaining CI failures; all 21 tests in the touched files pass under TZ=America/Sao_Paulo.

  • Bug Fixes
    • BridgeMetricsOverlay: require isDev && isAllowed; hide for non‑dev admins and gated devs.
    • quoteService.test.ts: align mock to .single() flow and call fetchQuote('q-1').
    • tests/contexts/AuthContext.test.tsx: add refreshSession to auth mock; make thenable .then() accept optional callback.
    • src/pages/Auth.test.tsx: mock useDevGate from @/hooks/admin; await forgot form via findByText (mounted with AnimatePresence).
    • src/tests/AdminLayout.test.tsx: mock MainLayout; expand @/integrations/supabase/client mock (rpc, like, ilike, single, etc.) to avoid double‑mount issues in jsdom.
    • FiltersPage.no-duplicate-sidebar.test.tsx: update path to src/pages/products/FiltersPage.tsx.

Written for commit 2923367. Summary will update on new commits. Review in cubic

Summary by CodeRabbit

Release Notes

  • Documentation

    • Documentação de decisões e fluxo de integração atualizada.
  • Bug Fixes

    • Refinamento de validação de acesso em componentes internos.
  • Tests

    • Ajustes em testes para melhor cobertura de autenticação, roteamento e consultas a dados.

Review Change Stack

Re-aplicado sobre a main fresca (nao copiado do #27 — produção divergiu):
- quoteService.test: mock alinhado a .single()/1-arg (fetchQuote)
- AuthContext.test: refreshSession no mock auth + thenable .then() defensivo (cb opcional)
- BridgeMetricsOverlay: gate exige isDev E isAllowed (bug de seguranca; admin nao-dev e dev sem SSOT ficam ocultos)
- Auth.test: useDevGate no mock @/hooks/admin + forgot-form async (AnimatePresence)
- AdminLayout.test: mocka MainLayout (cobertura real em MainLayout.breadcrumbs) + mock supabase robusto (rpc/like/single)
- FiltersPage guard: path src/pages/products/FiltersPage.tsx (pos-reorg)

Verificado com TZ=America/Sao_Paulo: 21/21 nos 6 arquivos; 0 regressao (demais falhas da main sao pre-existentes).
Copilot AI review requested due to automatic review settings May 21, 2026 16:31
@vercel
Copy link
Copy Markdown

vercel Bot commented May 21, 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 21, 2026 4:33pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 21, 2026

Walkthrough

PR atualiza documentation de decisões CI/testes (decision log v2) e sincroniza componente dev overlay, mocks Supabase e wrappers de renderização de testes. Inclui refactor do quote service API para remover parâmetro user e ajustes de gates de acesso.

Changes

Documentação de decisões CI e testes

Layer / File(s) Summary
Decision log v2 completo
docs/DECISION-LOG-2026-05-21-v2.md
Log documenta PR #35 (fix/ci-tests-green-onmain), comparação com #27 encerrado, ~20 arquivos restantes falhando com categorização de causas (drift de mocks/imports). Reforça regras permanentes (TZ, sandbox, GitHub MCP) e estabelece checklist de continuidade (gates, PRs enxutos, medição de fatias).

Infraestrutura de testes e gates

Layer / File(s) Summary
Gate de acesso do dev overlay
src/components/dev/BridgeMetricsOverlay.tsx, src/pages/Auth.test.tsx
BridgeMetricsOverlay agora respeita isAllowed além de isDev no gate. Auth.test fornece mock de useDevGate retornando { isAllowed: false, isDev: false }.
Quote service API refactor
src/services/__tests__/quoteService.test.ts
Mock Supabase ajustado de maybeSingle() para single(). Chamada de fetchQuote passa de 2 argumentos (id + user scope) para apenas id.
Expansão e alinhamento de mocks Supabase
src/tests/AdminLayout.test.tsx, tests/contexts/AuthContext.test.tsx
AdminLayout.test expande mock Supabase com refreshSession, operadores query (like, ilike, in, gte, lte, not), rpc, maybeSingle, single e then chainable. AuthContext.test ajusta refreshSession e then callback de profiles.update().eq() para resolver com { error: null }.
Async rendering e MainLayout wrapper
src/pages/Auth.test.tsx, src/tests/AdminLayout.test.tsx
Auth.test convertido para async com findByText para AnimatePresence. AdminLayout.test monta mock MainLayout com sidebar via data-testid e wrapper renderWithProviders passa <MainLayout>{ui}</MainLayout>.
FiltersPage test file reload
src/pages/__tests__/FiltersPage.no-duplicate-sidebar.test.tsx
Ajuste de linha carregando FiltersPage.tsx via readFileSync em teste de duplicação de sidebar.

🎯 2 (Simple) | ⏱️ ~12 minutes

🚥 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 identifica corretamente as mudanças principais: correção de 6 testes/componentes na main relacionada à onda CI-green, refletindo exatamente o escopo do PR.
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/ci-tests-green-onmain

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

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 6 files

Re-trigger cubic

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

Corrige divergências de mocks/asserções em testes que passaram a falhar na main e ajusta o gate do BridgeMetricsOverlay para respeitar o SSOT (isAllowed) além do papel dev, mantendo a suíte mais estável e alinhada ao comportamento de produção.

Changes:

  • Atualiza mocks do Supabase/Auth para refletir o contrato real (refreshSession, thenables, .single()).
  • Ajusta testes de UI para comportamento assíncrono (ex.: AnimatePresence) e para paths pós-reorg.
  • Endurece o gate do overlay de métricas exigindo isDev && isAllowed.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
tests/contexts/AuthContext.test.tsx Ajusta mock de auth e thenable para evitar drift com o fluxo real.
src/tests/AdminLayout.test.tsx Fortalece mocks (Supabase/MainLayout) para evitar hang/flakiness no jsdom.
src/services/__tests__/quoteService.test.ts Alinha mock/assinatura com fetchQuote(quoteId) e .single().
src/pages/Auth.test.tsx Corrige mocks de @/hooks/admin e espera assíncrona do forgot-password.
src/pages/__tests__/FiltersPage.no-duplicate-sidebar.test.tsx Atualiza path do FiltersPage após reorganização de pastas.
src/components/dev/BridgeMetricsOverlay.tsx Ajusta gate do overlay para exigir isAllowed além de isDev.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +27 to 28
const { isDev, isAllowed } = useDevGate();

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f735fed49a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

// Exige AMBOS: papel `dev` (isDev) E aprovação do gate (isAllowed).
// - admin com isAllowed=true mas isDev=false → NÃO vê (não é dev).
// - dev com isAllowed=false → NÃO vê (gate SSOT rejeitou, mesmo sendo dev).
if (!isDev || !isAllowed) return null;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Gate metrics hook with isAllowed too

After this change, isDev && !isAllowed users are blocked from rendering, but useBridgeMetrics is still initialized as useBridgeMetrics(isDev), so its side effects still run for denied users (notably the global backtick key handler in useBridgeMetrics that calls preventDefault). In this scenario the overlay is invisible but the shortcut is still intercepted, which is a behavioral regression introduced by the new isAllowed guard. Pass the combined gate (isDev && isAllowed) into the hook so runtime behavior matches the new visibility policy.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/tests/AdminLayout.test.tsx`:
- Line 58: O mock de then está usando cb?: any, o que enfraquece a validação do
contrato; substitua any por um tipo explícito que reflita o payload passado (por
exemplo uma função opcional (res: { data: unknown[]; error: Error | null }) =>
void) para a função de callback usada no vi.fn((cb?: any) => { ... }) do teste
AdminLayout.test.tsx, garantindo que o mock then valide a forma { data: [],
error: null } antes de invocar cb.

In `@tests/contexts/AuthContext.test.tsx`:
- Around line 112-113: O mock do thenable usa um callback tipado como any em
`then: vi.fn((cb?: any) => { cb?.({ error: null }); ... })`, enfraquecendo o
contrato do teste; substitua o any por um tipo específico (por exemplo declarar
um tipo AuthResponse = { error: string | null } ou similar) e alterar as duas
ocorrências do thenable para `cb?: (res: AuthResponse) => void`, garantindo que
o mock invoque o callback com um objeto compatível e preservando a assinatura
esperada do AuthContext.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 74d876ab-d27d-4b98-b4e1-b2e9b4d0099e

📥 Commits

Reviewing files that changed from the base of the PR and between 8028171 and 2923367.

📒 Files selected for processing (7)
  • docs/DECISION-LOG-2026-05-21-v2.md
  • src/components/dev/BridgeMetricsOverlay.tsx
  • src/pages/Auth.test.tsx
  • src/pages/__tests__/FiltersPage.no-duplicate-sidebar.test.tsx
  • src/services/__tests__/quoteService.test.ts
  • src/tests/AdminLayout.test.tsx
  • tests/contexts/AuthContext.test.tsx

not: vi.fn().mockReturnThis(),
maybeSingle: vi.fn().mockResolvedValue({ data: null, error: null }),
single: vi.fn().mockResolvedValue({ data: null, error: null }),
then: vi.fn((cb?: any) => { cb?.({ data: [], error: null }); return Promise.resolve({ data: [], error: null }); }),
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -nP '\b:\s*any\b|\bas\s+any\b' src/tests/AdminLayout.test.tsx

Repository: adm01-debug/promo-gifts-v4

Length of output: 52


🏁 Script executed:

#!/bin/bash
set -euo pipefail
ls -la src/tests/AdminLayout.test.tsx
sed -n '40,80p' src/tests/AdminLayout.test.tsx | nl -ba
rg -nP '\b:\s*any\b|\bas\s+any\b' src/tests/AdminLayout.test.tsx || true
rg -nP '\bunknown\b|\bany\b' src/tests/AdminLayout.test.tsx || true

Repository: adm01-debug/promo-gifts-v4

Length of output: 211


🏁 Script executed:

#!/bin/bash
set -euo pipefail
sed -n '40,80p' src/tests/AdminLayout.test.tsx | cat -n
rg -nP '\b:\s*any\b|\bas\s+any\b' src/tests/AdminLayout.test.tsx || true

Repository: adm01-debug/promo-gifts-v4

Length of output: 2282


🏁 Script executed:

#!/bin/bash
set -euo pipefail
rg -nP '\b:\s*any\b|\bas\s+any\b' src/tests/AdminLayout.test.tsx || true
rg -nP '\bunknown\b' src/tests/AdminLayout.test.tsx || true
rg -nP '\bany\b' src/tests/AdminLayout.test.tsx || true

Repository: adm01-debug/promo-gifts-v4

Length of output: 195


Remova any do callback do mock then no teste
Em src/tests/AdminLayout.test.tsx (linha 58), cb?: any quebra a validação de contrato e pode mascarar regressões no payload. Tipar o callback com o shape esperado mantém o teste mais seguro.

🔧 Sugestão de ajuste
-      then: vi.fn((cb?: any) => { cb?.({ data: [], error: null }); return Promise.resolve({ data: [], error: null }); }),
+      then: vi.fn((cb?: (result: { data: []; error: null }) => void) => {
+        const result: { data: []; error: null } = { data: [], error: null };
+        cb?.(result);
+        return Promise.resolve(result);
+      }),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
then: vi.fn((cb?: any) => { cb?.({ data: [], error: null }); return Promise.resolve({ data: [], error: null }); }),
then: vi.fn((cb?: (result: { data: []; error: null }) => void) => {
const result: { data: []; error: null } = { data: [], error: null };
cb?.(result);
return Promise.resolve(result);
}),
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/AdminLayout.test.tsx` at line 58, O mock de then está usando cb?:
any, o que enfraquece a validação do contrato; substitua any por um tipo
explícito que reflita o payload passado (por exemplo uma função opcional (res: {
data: unknown[]; error: Error | null }) => void) para a função de callback usada
no vi.fn((cb?: any) => { ... }) do teste AdminLayout.test.tsx, garantindo que o
mock then valide a forma { data: [], error: null } antes de invocar cb.

Comment on lines +112 to 113
then: vi.fn((cb?: any) => { cb?.({ error: null }); return Promise.resolve({ error: null }); }),
}),
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -nP '\b:\s*any\b|\bas\s+any\b' tests/contexts/AuthContext.test.tsx

Repository: adm01-debug/promo-gifts-v4

Length of output: 1219


🏁 Script executed:

#!/bin/bash
set -euo pipefail
FILE="tests/contexts/AuthContext.test.tsx"

echo "---- lines 95-140 ----"
nl -ba "$FILE" | sed -n '95,140p'

echo "---- lines 155-205 ----"
nl -ba "$FILE" | sed -n '155,205p'

Repository: adm01-debug/promo-gifts-v4

Length of output: 154


🏁 Script executed:

#!/bin/bash
set -euo pipefail
FILE="tests/contexts/AuthContext.test.tsx"

echo "---- lines 95-140 ----"
awk 'NR>=95 && NR<=140 {printf "%d:%s\n", NR, $0}' "$FILE"

echo "---- lines 155-205 ----"
awk 'NR>=155 && NR<=205 {printf "%d:%s\n", NR, $0}' "$FILE"

Repository: adm01-debug/promo-gifts-v4

Length of output: 4389


Tipar o callback dos thenables do mock (remover cb?: any)

Em tests/contexts/AuthContext.test.tsx, há then: vi.fn((cb?: any) => ...) nas linhas 112 e 168; o any enfraquece o contrato do mock justamente no fluxo crítico do AuthContext. Trocar o callback para um tipo específico evita regressões silenciosas.

🔧 Sugestão de ajuste
-              then: vi.fn((cb?: any) => { cb?.({ error: null }); return Promise.resolve({ error: null }); }),
+              then: vi.fn((cb?: (result: { error: null }) => void) => {
+                const result: { error: null } = { error: null };
+                cb?.(result);
+                return Promise.resolve(result);
+              }),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
then: vi.fn((cb?: any) => { cb?.({ error: null }); return Promise.resolve({ error: null }); }),
}),
then: vi.fn((cb?: (result: { error: null }) => void) => {
const result: { error: null } = { error: null };
cb?.(result);
return Promise.resolve(result);
}),
}),
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/contexts/AuthContext.test.tsx` around lines 112 - 113, O mock do
thenable usa um callback tipado como any em `then: vi.fn((cb?: any) => { cb?.({
error: null }); ... })`, enfraquecendo o contrato do teste; substitua o any por
um tipo específico (por exemplo declarar um tipo AuthResponse = { error: string
| null } ou similar) e alterar as duas ocorrências do thenable para `cb?: (res:
AuthResponse) => void`, garantindo que o mock invoque o callback com um objeto
compatível e preservando a assinatura esperada do AuthContext.

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