Skip to content

test+fix: 10 testes drifted (path/mock/asserts) + bug UX SocialLoginButtons#38

Merged
adm01-debug merged 1 commit into
mainfrom
fix/ci-green-remaining-20
May 22, 2026
Merged

test+fix: 10 testes drifted (path/mock/asserts) + bug UX SocialLoginButtons#38
adm01-debug merged 1 commit into
mainfrom
fix/ci-green-remaining-20

Conversation

@adm01-debug

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

Copy link
Copy Markdown
Owner

O que este PR faz

Corrige 10 arquivos de teste que quebraram com o drift pós re-import do Lovable. Todos validados verdes localmente (TZ=America/Sao_Paulo, vitest forks).

✅ Drift de teste (9 arquivos)

  • Path: CatalogFilteringLogic, SSOCallbackPage (imports pós-reorg) + asserts OAuth p/ novo formato explainOAuthError
  • Mock — múltiplos vi.mock() no mesmo path (vitest faz hoist, só o último factory vence → exports somem): mesclados em 1 factory por path — useQuoteBuilderState.unit/shipping, ConnectionUI, ConnectionsOverviewTable
  • Mock — path errado: useAdvancedFilters.unit (./useExternalDatabase@/hooks/intelligence/useExternalDatabase)
  • Mock — importActual: AuthContext (preserva signOut real; try/catch tolera falha remota — estado limpo no finally)
  • Assert — saída real: security-integration (sanitizeHtml: button/a fora da allowlist do DOMPurify → vira texto)

🐛 Bug real de SUT corrigido (1 arquivo)

  • SocialLoginButtons.tsx: mapOAuthError retornava o código cru 'provider_is_not_enabled' direto no toast do usuário (todos os outros ramos retornam PT-BR amigável). Restaurada mensagem amigável. @po confirmar a cópia.

⚠️ Fora deste PR — precisam de decisão/validação

  • useCatalogState.unit: fix escrito, mas o SUT real carrega árvore pesada e crasha o worker de 4GB do sandbox (ERR_IPC_CHANNEL_CLOSED). Validar no CI.
  • 8 arquivos = regressão real de SUT / design / feature removida (NÃO mascarados):
    • SidebarNavGroup.tsx: hover:shadow-* glow + border-primary/30 com glow (viola regra "sem glow") e lógica de destaque-ativo regrediu (SidebarNoShadow + history + suspense, 14 testes). Provável re-import reverteu o SUT.
    • AuthBranding (3 testes): ContinuousRockets não existe mais (removido/inlinado).
    • QuoteBuilderDiscountAdvanced (3): inputs de desconto saíram de QuoteBuilderSummaryColumn.
    • AppLogo.visual / AuthBranding.visual: drift de classes visuais (confirmar design).
    • ScenarioSimulation: 1 assert de lógica (shipping).
  • Fatias tests/ e e2e/ ainda não medidas.

PR aberto não-draft para o CI rodar de fato.


Summary by cubic

Restores a friendly OAuth error message in SocialLoginButtons and repairs drifted tests after the Lovable re-import to get CI back to green.

  • Bug Fixes

    • SocialLoginButtons: show a user-friendly PT-BR message when the provider is not enabled, instead of the raw provider_is_not_enabled code.
  • Refactors

    • Consolidated multiple vi.mock() calls per path into a single factory in tests (e.g., @/hooks/quotes, @/hooks/intelligence) to avoid hoist overwrites.
    • Fixed import paths after reorg (e.g., catalog hooks now under hooks/products/*; SSOCallbackPage import updated).
    • Updated OAuth callback tests to assert error and error_description query params.
    • Adjusted sanitizeHtml tests to match DOMPurify behavior (disallowed button/a become text).
    • AuthContext tests now use importActual to preserve real authService methods and wrap signOut in try/catch.

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

Summary by CodeRabbit

Notas de Versão

  • Correções de Bugs

    • Melhorada mensagem de erro para cenários de login social quando o provedor não está habilitado.
  • Testes

    • Otimização da estrutura de testes e consolidação de configurações de mock para melhor manutenibilidade.

Review Change Stack

… SocialLoginButtons

Drift de teste pos-reimport Lovable: paths de import, consolidacao de multiplos vi.mock no mesmo path, asserts (OAuth/sanitizeHtml), importActual em AuthContext. SUT: mapOAuthError mostrava codigo cru no toast (restaurada msg PT-BR).
Copilot AI review requested due to automatic review settings May 21, 2026 17:50
@vercel

vercel Bot commented May 21, 2026

Copy link
Copy Markdown

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 5:51pm

@supabase

supabase Bot commented May 21, 2026

Copy link
Copy Markdown

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 ↗︎.

@coderabbitai

coderabbitai Bot commented May 21, 2026

Copy link
Copy Markdown

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: 29c0596d-a5be-4c48-8688-0c0f52aafcad

📥 Commits

Reviewing files that changed from the base of the PR and between d206897 and 5575a63.

📒 Files selected for processing (10)
  • src/components/admin/connections/__tests__/ConnectionUI.test.tsx
  • src/components/admin/connections/__tests__/ConnectionsOverviewTable.test.tsx
  • src/components/auth/SocialLoginButtons.tsx
  • src/contexts/AuthContext.test.tsx
  • src/hooks/__tests__/useAdvancedFilters.unit.test.tsx
  • src/hooks/__tests__/useQuoteBuilderState.shipping.test.tsx
  • src/hooks/__tests__/useQuoteBuilderState.unit.test.tsx
  • src/lib/security/__tests__/security-integration.test.ts
  • src/pages/__tests__/SSOCallbackPage.test.tsx
  • src/tests/CatalogFilteringLogic.test.tsx

Walkthrough

PR consolida mocks de testes através de múltiplos arquivos, melhora resiliência de testes com try/catch em operações remotas, atualiza asserções para HTML sanitizado e parsing de query strings, corrige caminhos de importação e localiza mensagem de erro OAuth.

Changes

Test Infrastructure e Assertions

Layer / File(s) Summary
Consolidação de Mocks de Intelligence Hooks
src/components/admin/connections/__tests__/ConnectionUI.test.tsx, src/components/admin/connections/__tests__/ConnectionsOverviewTable.test.tsx
Reorganiza vi.mock('@/hooks/intelligence', ...) consolidando useConnectionsOverview e useConnectionTester em blocos únicos com declarações explícitas via vi.fn() em lugar de múltiplas definições separadas.
Consolidação de Mocks de Quotes Hooks
src/hooks/__tests__/useQuoteBuilderState.shipping.test.tsx, src/hooks/__tests__/useQuoteBuilderState.unit.test.tsx
Unifica múltiplas chamadas vi.mock('@/hooks/quotes', ...) em blocos únicos, centralizando useQuotes, useQuoteTemplates, useSellerDiscountLimits, useDiscountApproval e useAutoSaveQuote. Atualiza asserção de erro para "Selecione a forma de pagamento".
Resiliência do AuthContext Test
src/contexts/AuthContext.test.tsx
Reestrutura mock de authService com importOriginal preservando implementação e sobrescrevendo seletivamente métodos. Envolve chamadas signOut() em try/catch para tolerar falhas remotas sem quebrar validações locais.
Asserções Robustas e Importações
src/lib/security/__tests__/security-integration.test.ts, src/pages/__tests__/SSOCallbackPage.test.tsx, src/hooks/__tests__/useAdvancedFilters.unit.test.tsx, src/tests/CatalogFilteringLogic.test.tsx
Atualiza asserções de sanitização HTML de expect tags para expect apenas texto. Melhora SSOCallbackPage com URLSearchParams em lugar de regex para parsing. Corrige paths de importação: useAdvancedFilters usa alias @/hooks/intelligence/useExternalDatabase, CatalogFilteringLogic usa ../hooks/products/....
Mensagem de Erro OAuth Localizada
src/components/auth/SocialLoginButtons.tsx
mapOAuthError retorna mensagem PT-BR descritiva ("Google login ainda não habilitado, contate o administrador") para "provider is not enabled" em lugar de texto genérico.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 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 as mudanças principais: correção de 10 testes e um bug de UX no SocialLoginButtons.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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-green-remaining-20

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

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

Copy link
Copy Markdown

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: 5575a63768

ℹ️ 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".

const m = raw.toLowerCase();
if (m.includes('unsupported provider') || m.includes('provider is not enabled')) {
return 'provider_is_not_enabled';
return 'O login com Google ainda não está habilitado. Entre em contato com o administrador.';

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 Preserve disabled-provider code for downstream error mapping

When Supabase returns unsupported provider / provider is not enabled, this branch now returns a free-form PT-BR sentence instead of the machine code. In Auth.tsx, handleSocialError calls resolveOAuthError(message) and relies on code-based mapping (e.g., provider_is_not_enabled) to mark isConfig=true; with plain text, it falls back to a generic non-config error, so the UI incorrectly shows “Tentar Google Novamente” for a non-recoverable configuration issue and loses the specific admin hint.

Useful? React with 👍 / 👎.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

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 updates several Vitest unit/integration tests that drifted after a code re-org (notably import paths and consolidated vi.mock factories), and adjusts a user-facing OAuth error message in SocialLoginButtons.

Changes:

  • Updated test imports to new module locations (e.g., products hooks, SSO callback page).
  • Consolidated multiple vi.mock() calls per module into single factories to avoid Vitest hoist/overwrite issues.
  • Aligned assertions with current runtime behavior (OAuth redirect params; DOMPurify allowlist output) and adjusted one OAuth error mapping message.

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/tests/CatalogFilteringLogic.test.tsx Updates hook/type import paths to post-reorg locations.
src/pages/tests/SSOCallbackPage.test.tsx Updates SSO callback import and asserts redirect query params via URLSearchParams.
src/lib/security/tests/security-integration.test.ts Updates sanitizeHtml expectations to match current allowlist behavior (tags stripped to text).
src/hooks/tests/useQuoteBuilderState.unit.test.tsx Consolidates @/hooks/quotes mocks and updates a validation toast expectation.
src/hooks/tests/useQuoteBuilderState.shipping.test.tsx Consolidates @/hooks/quotes mocks and keeps AuthContext mocked separately.
src/hooks/tests/useAdvancedFilters.unit.test.tsx Fixes mock path/importActual to match aliased module location.
src/contexts/AuthContext.test.tsx Switches to partial mock of authService and tolerates remote signOut failures in tests.
src/components/auth/SocialLoginButtons.tsx Changes OAuth error mapping for “provider not enabled” to a PT-BR message.
src/components/admin/connections/tests/ConnectionUI.test.tsx Consolidates intelligence hook mocks into a single factory.
src/components/admin/connections/tests/ConnectionsOverviewTable.test.tsx Consolidates intelligence hook mocks into a single factory.

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

Comment on lines 14 to 18
function mapOAuthError(raw: string): string {
const m = raw.toLowerCase();
if (m.includes('unsupported provider') || m.includes('provider is not enabled')) {
return 'provider_is_not_enabled';
return 'O login com Google ainda não está habilitado. Entre em contato com o administrador.';
}
Comment on lines 78 to 84
await act(async () => {
try {
await result.current.signOut();
} catch {
/* falha remota tolerada */
}
});
renderAt('/auth/callback?code=expired');
await waitFor(() => expect(navigateMock).toHaveBeenCalled());
expect(navigateMock.mock.calls[0][0]).toMatch(/\/login\?error=invalid_grant/);
const p3 = new URLSearchParams(String(navigateMock.mock.calls[0][0]).split('?')[1]);

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

No issues found across 10 files

Re-trigger cubic

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