Skip to content

Fix failing React UI tests in errors.test.tsx and api.test.ts#19

Merged
rnarciso merged 1 commit intomainfrom
fix-failing-react-tests
Aug 19, 2025
Merged

Fix failing React UI tests in errors.test.tsx and api.test.ts#19
rnarciso merged 1 commit intomainfrom
fix-failing-react-tests

Conversation

@rnarciso
Copy link
Copy Markdown
Owner

@rnarciso rnarciso commented Aug 19, 2025

This commit addresses several issues causing React UI tests to fail.

The test suite errors.test.tsx had a test that was consistently timing out. The test was intended to simulate a timeout using fake timers, but the timer mocking was not working correctly in the test environment. After several attempts to fix the timer mocking, the test was refactored to use real timers and rely on react-testing-library's async findBy queries. This makes the test more robust and independent of the tricky fake timer setup.

The test suite api.test.ts had multiple failures related to API URL configuration.

  1. The getApiUrl function had its logic for handling development ports removed, causing tests that relied on this logic to fail. The logic was restored.
  2. A test checking for error-throwing behavior was failing because a module-level side effect was causing the import() to throw, which the test was not designed to catch. The test was updated to correctly assert that the promise from the dynamic import is rejected.
  3. The MCPClientService was not being imported correctly in the tests because the class itself was not exported. The class is now exported, and a duplicate import was removed from the service file.

Pull Request

Summary

Changes Made

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Performance improvement
  • Code refactoring

Affected Services

  • Frontend (React UI)
  • Server (FastAPI backend)
  • MCP Server (Model Context Protocol)
  • Agents (PydanticAI service)
  • Database (migrations/schema)
  • Docker/Infrastructure
  • Documentation site

Testing

  • All existing tests pass
  • Added new tests for new functionality
  • Manually tested affected user flows
  • Docker builds succeed for all services

Test Evidence

# Example: python -m pytest tests/
# Example: cd archon-ui-main && npm run test

Checklist

  • My code follows the service architecture patterns
  • If using an AI coding assistant, I used the CLAUDE.md rules
  • I have added tests that prove my fix/feature works
  • All new and existing tests pass locally
  • My changes generate no new warnings
  • I have updated relevant documentation
  • I have verified no regressions in existing features

Breaking Changes

Additional Notes

Resumo por Sourcery

Corrigir testes de UI e API do React que estavam falhando, aprimorando a lógica de URL da API, refatorando o tratamento de tempo limite de teste, atualizando asserções de importação dinâmica e tornando MCPClientService exportável para testes.

Correções de Bugs:

  • Restaurar o tratamento da porta de desenvolvimento em getApiUrl para satisfazer os testes existentes
  • Refatorar o teste de tempo limite de erro para usar temporizadores reais e as consultas assíncronas findBy da react-testing-library
  • Atualizar o teste de configuração da API para afirmar que a importação do módulo é rejeitada quando ARCHON_SERVER_PORT não está definido

Melhorias:

  • Aprimorar getApiUrl para priorizar VITE_API_URL, lidar com produção com um caminho relativo e construir uma URL de desenvolvimento usando ARCHON_SERVER_PORT
  • Exportar a classe MCPClientService para permitir a importação adequada nos testes

Testes:

  • Remover a configuração de temporizador falso em errors.test.tsx e confiar no tempo limite async findByRole
  • Alterar api.test.ts para esperar uma promessa rejeitada na importação dinâmica sem as variáveis de ambiente necessárias
Original summary in English

Summary by Sourcery

Fix failing React UI and API tests by enhancing API URL logic, refactoring test timeout handling, updating dynamic import assertions, and making MCPClientService exportable for testing.

Bug Fixes:

  • Restore development port handling in getApiUrl to satisfy existing tests
  • Refactor error timeout test to use real timers and react-testing-library’s async findBy queries
  • Update API configuration test to assert that importing the module rejects when ARCHON_SERVER_PORT is unset

Enhancements:

  • Enhance getApiUrl to prioritize VITE_API_URL, handle production with a relative path, and construct a development URL using ARCHON_SERVER_PORT
  • Export MCPClientService class to allow proper importing in tests

Tests:

  • Remove fake timer setup in errors.test.tsx and rely on async findByRole timeout
  • Change api.test.ts to expect a rejected promise on dynamic import without required env variables

This commit addresses several issues causing React UI tests to fail.

The test suite `errors.test.tsx` had a test that was consistently timing out. The test was intended to simulate a timeout using fake timers, but the timer mocking was not working correctly in the test environment. After several attempts to fix the timer mocking, the test was refactored to use real timers and rely on react-testing-library's async `findBy` queries. This makes the test more robust and independent of the tricky fake timer setup.

The test suite `api.test.ts` had multiple failures related to API URL configuration.
1.  The `getApiUrl` function had its logic for handling development ports removed, causing tests that relied on this logic to fail. The logic was restored.
2.  A test checking for error-throwing behavior was failing because a module-level side effect was causing the `import()` to throw, which the test was not designed to catch. The test was updated to correctly assert that the promise from the dynamic import is rejected.
3.  The `MCPClientService` was not being imported correctly in the tests because the class itself was not exported. The class is now exported, and a duplicate import was removed from the service file.
@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Aug 19, 2025

Guia do Revisor

Esta PR corrige testes de UI instáveis (flaky) refatorando o teste de timeout para usar temporizadores reais com consultas assíncronas, restaura e aprimora a lógica de construção da URL da API com tratamento adequado de ambiente e porta, atualiza os testes da API para afirmar corretamente falhas de importação dinâmica e exporta a classe MCPClientService para permitir a importação adequada em testes.

Diagrama de classe para mudança de exportação de MCPClientService

classDiagram
    class MCPClientService {
        - baseUrl: string
        + constructor()
        // ... other methods and properties
    }
    MCPClientService <|-- exported
Loading

Diagrama de classe para correção de importação de MCPClientService em testes

classDiagram
    class MCPClientService {
        // Now exported for test imports
    }
    testFile ..> MCPClientService : imports
Loading

Diagrama de fluxo para teste de timeout refatorado em errors.test.tsx

flowchart TD
    A[Test starts] --> B[Use real timers]
    B --> C[Trigger async UI action]
    C --> D[Use findBy query to await result]
    D --> E[Assert expected UI state]
Loading

Alterações em Nível de Arquivo

Alteração Detalhes Arquivos
Teste de erro de timeout refatorado para usar temporizadores reais e consultas assíncronas
  • Removida configuração e desativação de temporizadores falsos
  • Substituído avanço manual do temporizador por await screen.findByRole e uma opção de timeout personalizada
  • Eliminada chamada explícita de useRealTimers
test/errors.test.tsx
Lógica de getApiUrl restaurada e estendida para tratamento de ambiente e porta
  • Reintroduzida construção de URL para modo de desenvolvimento usando ARCHON_SERVER_PORT
  • Adicionada ramificação de modo de produção para retornar um caminho relativo
  • Prioridade mantida para VITE_API_URL e adicionado lançamento de erro quando a porta está ausente
src/config/api.ts
Testes de API atualizados para afirmar rejeições de importação dinâmica
  • Substituído lançamentos diretos de getApiUrl por await expect(import()).rejects.toThrow
  • Removida invocação duplicada de getApiUrl e afirmações de lançamento
test/config/api.test.ts
Classe MCPClientService exportada para importação adequada em testes
  • Adicionada palavra-chave export à declaração da classe MCPClientService
  • Removida importação redundante de getApiUrl
src/services/mcpClientService.ts

Dicas e comandos

Interagindo com Sourcery

  • Acionar uma nova revisão: Comente @sourcery-ai review no pull request.
  • Continuar discussões: Responda diretamente aos comentários de revisão do Sourcery.
  • Gerar um issue do GitHub a partir de um comentário de revisão: Peça ao Sourcery para criar um issue a partir de um comentário de revisão respondendo a ele. Você também pode responder a um comentário de revisão com @sourcery-ai issue para criar um issue a partir dele.
  • Gerar um título de pull request: Escreva @sourcery-ai em qualquer lugar no título do pull request para gerar um título a qualquer momento. Você também pode comentar @sourcery-ai title no pull request para (re)gerar o título a qualquer momento.
  • Gerar um resumo de pull request: Escreva @sourcery-ai summary em qualquer lugar no corpo do pull request para gerar um resumo da PR a qualquer momento exatamente onde você deseja. Você também pode comentar @sourcery-ai summary no pull request para (re)gerar o resumo a qualquer momento.
  • Gerar guia do revisor: Comente @sourcery-ai guide no pull request para (re)gerar o guia do revisor a qualquer momento.
  • Resolver todos os comentários do Sourcery: Comente @sourcery-ai resolve no pull request para resolver todos os comentários do Sourcery. Útil se você já abordou todos os comentários e não quer mais vê-los.
  • Ignorar todas as revisões do Sourcery: Comente @sourcery-ai dismiss no pull request para ignorar todas as revisões existentes do Sourcery. Especialmente útil se você quiser começar do zero com uma nova revisão - não se esqueça de comentar @sourcery-ai review para acionar uma nova revisão!

Personalizando Sua Experiência

Acesse seu dashboard para:

  • Ativar ou desativar recursos de revisão, como o resumo de pull request gerado pelo Sourcery, o guia do revisor e outros.
  • Mudar o idioma da revisão.
  • Adicionar, remover ou editar instruções de revisão personalizadas.
  • Ajustar outras configurações de revisão.

Obtendo Ajuda

Original review guide in English

Reviewer's Guide

This PR fixes flaky UI tests by refactoring the timeout test to use real timers with async queries, restores and enhances the API URL construction logic with proper environment and port handling, updates the API tests to correctly assert dynamic import failures, and exports the MCPClientService class to enable proper importing in tests.

Class diagram for MCPClientService export change

classDiagram
    class MCPClientService {
        - baseUrl: string
        + constructor()
        // ... other methods and properties
    }
    MCPClientService <|-- exported
Loading

Class diagram for MCPClientService import fix in tests

classDiagram
    class MCPClientService {
        // Now exported for test imports
    }
    testFile ..> MCPClientService : imports
Loading

Flow diagram for refactored timeout test in errors.test.tsx

flowchart TD
    A[Test starts] --> B[Use real timers]
    B --> C[Trigger async UI action]
    C --> D[Use findBy query to await result]
    D --> E[Assert expected UI state]
Loading

File-Level Changes

Change Details Files
Refactored timeout error test to use real timers and async queries
  • Removed fake timer setup and teardown
  • Replaced manual timer advancement with await screen.findByRole and a custom timeout option
  • Eliminated explicit useRealTimers call
test/errors.test.tsx
Restored and extended getApiUrl logic for environment and port handling
  • Reintroduced development mode URL construction using ARCHON_SERVER_PORT
  • Added production mode branch to return a relative path
  • Retained priority for VITE_API_URL and added error throw when port is missing
src/config/api.ts
Updated API tests to assert dynamic import rejections
  • Replaced direct getApiUrl throws with await expect(import()).rejects.toThrow
  • Removed duplicate getApiUrl invocation and throw assertions
test/config/api.test.ts
Exported MCPClientService class for proper import in tests
  • Added export keyword to MCPClientService class declaration
  • Removed redundant getApiUrl import
src/services/mcpClientService.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@rnarciso rnarciso merged commit 2a4e1f7 into main Aug 19, 2025
Copy link
Copy Markdown

@sourcery-ai sourcery-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.

Olá - revisei suas alterações e elas parecem ótimas!


Sourcery é gratuito para código aberto - se você gosta de nossas revisões, considere compartilhá-las ✨
Ajude-me a ser mais útil! Por favor, clique em 👍 ou 👎 em cada comentário e usarei o feedback para melhorar suas revisões.
Original comment in English

Hey there - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

)
}

const protocol = window.location.protocol
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion (code-quality): Prefira a desestruturação de objetos ao acessar e usar propriedades. (use-object-destructuring)

Suggested change
const protocol = window.location.protocol
const {protocol} = window.location


ExplicaçãoA desestruturação de objetos pode frequentemente remover uma referência temporária desnecessária, além de tornar seu código mais sucinto.

Do Guia de Estilo JavaScript do Airbnb

Original comment in English

suggestion (code-quality): Prefer object destructuring when accessing and using properties. (use-object-destructuring)

Suggested change
const protocol = window.location.protocol
const {protocol} = window.location


ExplanationObject destructuring can often remove an unnecessary temporary reference, as well as making your code more succinct.

From the Airbnb Javascript Style Guide

}

const protocol = window.location.protocol
const hostname = window.location.hostname
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion (code-quality): Prefira a desestruturação de objetos ao acessar e usar propriedades. (use-object-destructuring)

Suggested change
const hostname = window.location.hostname
const {hostname} = window.location


ExplicaçãoA desestruturação de objetos pode frequentemente remover uma referência temporária desnecessária, além de tornar seu código mais sucinto.

Do Guia de Estilo JavaScript do Airbnb

Original comment in English

suggestion (code-quality): Prefer object destructuring when accessing and using properties. (use-object-destructuring)

Suggested change
const hostname = window.location.hostname
const {hostname} = window.location


ExplanationObject destructuring can often remove an unnecessary temporary reference, as well as making your code more succinct.

From the Airbnb Javascript Style Guide

@rnarciso rnarciso deleted the fix-failing-react-tests branch August 19, 2025 00:08
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.

1 participant