fix(tests): repara 6 testes/componente sobre a main (onda CI-green)#35
Conversation
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).
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughPR 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. ChangesDocumentação de decisões CI e testes
Infraestrutura de testes e gates
🎯 2 (Simple) | ⏱️ ~12 minutes 🚥 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
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.
| const { isDev, isAllowed } = useDevGate(); | ||
|
|
There was a problem hiding this comment.
💡 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; |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
📒 Files selected for processing (7)
docs/DECISION-LOG-2026-05-21-v2.mdsrc/components/dev/BridgeMetricsOverlay.tsxsrc/pages/Auth.test.tsxsrc/pages/__tests__/FiltersPage.no-duplicate-sidebar.test.tsxsrc/services/__tests__/quoteService.test.tssrc/tests/AdminLayout.test.tsxtests/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 }); }), |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
rg -nP '\b:\s*any\b|\bas\s+any\b' src/tests/AdminLayout.test.tsxRepository: 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 || trueRepository: 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 || trueRepository: 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 || trueRepository: 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.
| 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.
| then: vi.fn((cb?: any) => { cb?.({ error: null }); return Promise.resolve({ error: null }); }), | ||
| }), |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
rg -nP '\b:\s*any\b|\bas\s+any\b' tests/contexts/AuthContext.test.tsxRepository: 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.
| 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.
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)quoteService.test.tseq().eq().maybeSingle(); produção éeq().single()1-argtests/contexts/AuthContext.test.tsxrefreshSessionno mock auth; thenable.then()chamado sem args (produção usa.then()vazio)BridgeMetricsOverlay.tsxisDev; precisaisDev && isAllowed(admin não-dev e dev sem SSOT devem ficar ocultos)Auth.test.tsx@/hooks/adminsemuseDevGate; forgot-form monta via AnimatePresence (assíncrono)AdminLayout.test.tsxFiltersPage.no-duplicate-sidebar.test.tsxsrc/pages/products/)O
MainLayoutreal tem cobertura dedicada emtests/components/layout/MainLayout.breadcrumbs.test.tsx, então mocká-lo aqui não perde cobertura.Verificação
mainsão pré-existentes (confirmado rodando-as em working tree limpo, sem estes fixes).Nota
Não esgota o CI: a
maintem ~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
mainand updates the dev metrics overlay to require both dev role and gate approval. Addsdocs/DECISION-LOG-2026-05-21-v2.mdmapping remaining CI failures; all 21 tests in the touched files pass underTZ=America/Sao_Paulo.BridgeMetricsOverlay: requireisDev && isAllowed; hide for non‑dev admins and gated devs.quoteService.test.ts: align mock to.single()flow and callfetchQuote('q-1').tests/contexts/AuthContext.test.tsx: addrefreshSessionto auth mock; make thenable.then()accept optional callback.src/pages/Auth.test.tsx: mockuseDevGatefrom@/hooks/admin; await forgot form viafindByText(mounted withAnimatePresence).src/tests/AdminLayout.test.tsx: mockMainLayout; expand@/integrations/supabase/clientmock (rpc,like,ilike,single, etc.) to avoid double‑mount issues in jsdom.FiltersPage.no-duplicate-sidebar.test.tsx: update path tosrc/pages/products/FiltersPage.tsx.Written for commit 2923367. Summary will update on new commits. Review in cubic
Summary by CodeRabbit
Release Notes
Documentation
Bug Fixes
Tests