Skip to content

Fix DateInput tests and standardize date handling#1069

Merged
jvictordev1 merged 6 commits intomainfrom
hotfix/fix-date-input-tests-16465431169864620625
Mar 13, 2026
Merged

Fix DateInput tests and standardize date handling#1069
jvictordev1 merged 6 commits intomainfrom
hotfix/fix-date-input-tests-16465431169864620625

Conversation

@lucasn4s
Copy link
Collaborator

Fixed failing unit tests for the DateInput component by improving date mocking, standardizing date handling across components, and resolving prop validation and Vue warnings.


PR created automatically by Jules for task 16465431169864620625 started by @lucasn4s

This commit addresses the following issues:
1. Adds 'date' to the allowed input types in `inputTypes.js` to resolve prop validation warnings.
2. Standardizes date handling in `DateInput`, `InlineDateInput`, `MonthSelectorGrid`, and `YearSelectorGrid` by using Luxon's `DateTime.now()` instead of native `new Date()`. This ensures consistent behavior and reliable mocking in tests.
3. Adds the missing Luxon import to `InlineDateInput.vue`.
4. Fixes a Vue warning in `DateInput.vue` by adding the `placeholder` prop to `BaseMobileInput.vue`.
5. Removes temporary test log files.

These changes ensure that date-related tests are robust against current date variations and follow the project's standards.

Co-authored-by: lucasn4s <17988272+lucasn4s@users.noreply.github.com>
@google-labs-jules
Copy link
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@github-actions github-actions bot added the 🐛 Bug Algo não está funcionando label Mar 13, 2026
google-labs-jules bot and others added 3 commits March 13, 2026 13:26
1. Standardized Luxon mocking in `SelectorGridHighlight.spec.js` by adding `Settings.now` mock and proper cleanup.
2. Removed redundant hardcoded `placeholder=""` from `BaseMobileInput.vue` and updated related snapshot.
3. Ensured `DateTime` is properly imported in all components where it was recently introduced.
4. Resolved 'Invalid prop type' warnings by adding 'date' to `inputTypes.js`.
5. Cleaned up workspace from temporary test log files.

These changes ensure robust, mockable date handling and reliable CI results.

Co-authored-by: lucasn4s <17988272+lucasn4s@users.noreply.github.com>
@jvictordev1
Copy link
Contributor

Ao remover a atribuição de um placeholder vazio no input do arquivo BaseMobileInput a label fica flutuando em cima do placeholder do componente, dando um efeito visual de sobreposição de textos. A mesma coisa acontecia na validação internalValue || placeholder do input de data. Além disso, faz sentido remover o atributo placeholder da tag div que forma o componente do tipo date.

Outro ponto é a presença da prop placeholder no BaseMobileInput. Não acho que seja necessário pois o atualmente esse componente é interno da biblioteca, não sendo instanciado individualmente na aplicação cliente e sim através de outros componentes de input. Logo o mesmo herda todas as props (já documentadas) de seus componentes pai.

@lucasn4s
Copy link
Collaborator Author

@jules Revise as mudanças deste PR e foque apenas em corrigir os testes do DateInput e gerenciamento de data.

@google-labs-jules
Copy link
Contributor

@jules Revise as mudanças deste PR e foque apenas em corrigir os testes do DateInput e gerenciamento de data.

Entendido. Revisei as mudanças e foquei exclusivamente na padronização do gerenciamento de datas e na correção dos testes relacionados.

Resumo das ações:

  1. Padronizei o uso de DateTime.now() (Luxon) em vez de new Date() nos componentes InlineDateInput, MonthSelectorGrid e YearSelectorGrid para permitir o mocking correto através do Luxon.
  2. Adicionei o mocking de Settings.now do Luxon no teste SelectorGridHighlight.spec.js, garantindo consistência com o tempo do sistema e evitando falhas em mudanças de mês.
  3. Mantive a adição do tipo date em inputTypes.js para resolver os avisos de validação de prop no DateInput.
  4. Reverti alterações não relacionadas no BaseMobileInput e DateInput (placeholder).
  5. Removi arquivos de log temporários.

This commit focuses on correcting unit test failures for the DateInput component and standardizing date management across the library.

Key changes:
- Standardized date handling by replacing 'new Date()' with Luxon's 'DateTime.now()' in InlineDateInput, MonthSelectorGrid, and YearSelectorGrid.
- Implemented robust mocking in SelectorGridHighlight.spec.js by synchronizing Luxon's Settings.now with Vitest's system time.
- Added 'date' to allowed input types in inputTypes.js to resolve Vue prop validation warnings.
- Cleaned up unrelated changes and temporary log files.

These modifications ensure that date-related components and tests are stable across month transitions and adhere to project standards.

Co-authored-by: lucasn4s <17988272+lucasn4s@users.noreply.github.com>
@lucasn4s
Copy link
Collaborator Author

Falta atualizar a versão do pacote no package.json e package-lock.json

@google-labs-jules
Copy link
Contributor

Falta atualizar a versão do pacote no package.json e package-lock.json

Corrigido. Atualizei a versão do pacote para 3.154.12 no package.json e package-lock.json.

- Updated package version to 3.154.12 in package.json and package-lock.json.
- Standardized date handling using Luxon in InlineDateInput, MonthSelectorGrid, and YearSelectorGrid.
- Improved mocking in SelectorGridHighlight.spec.js.
- Resolved 'date' input type validation warning.
- Reverted unrelated changes as per PR feedback.

Co-authored-by: lucasn4s <17988272+lucasn4s@users.noreply.github.com>
@jvictordev1 jvictordev1 merged commit 714dc25 into main Mar 13, 2026
8 checks passed
@jvictordev1 jvictordev1 deleted the hotfix/fix-date-input-tests-16465431169864620625 branch March 13, 2026 19:39
@greptile-apps
Copy link

greptile-apps bot commented Mar 14, 2026

Greptile Summary

Este PR corrige testes unitários que falhavam no componente DateInput ao padronizar o tratamento de datas para usar exclusivamente o Luxon (DateTime.now()) nos componentes InlineDateInput, MonthSelectorGrid e YearSelectorGrid, além de ajustar os mocks nos testes para incluir Settings.now do Luxon.

Principais mudanças:

  • InlineDateInput.vue: substitui new Date() por DateTime.now().toJSDate() para garantir que mocks de Settings.now funcionem corretamente.
  • MonthSelectorGrid.vue e YearSelectorGrid.vue: adicionado import do Luxon e padronizado o uso de DateTime.now().year no lugar de new Date().getFullYear().
  • SelectorGridHighlight.spec.js: adicionado afterEach para limpar vi.useRealTimers() e restaurar Settings.now entre testes; beforeEach agora também mocka Settings.now do Luxon.
  • inputTypes.js: adicionado 'date' à lista de tipos válidos, removendo o aviso de validação de prop gerado quando DateInput usa type="date" no BaseInput.
  • Bump de versão: 3.154.113.154.12.

Confidence Score: 4/5

  • Este PR é seguro para merge com risco mínimo — corrige testes sem alterar comportamento em produção.
  • As mudanças são pontuais, bem focadas e não introduzem regressões. O único ponto de atenção é que default: DateTime.now().year em defineProps do MonthSelectorGrid é avaliado no nível de módulo (tempo de carregamento), não por instância, diferente do const todayYear em YearSelectorGrid. Como os anos real e mockado coincidem (2026), os testes passam, mas isso representa uma fragilidade potencial para testes futuros que precisem mockar um ano diferente.
  • Atenção especial para MonthSelectorGrid.vue (linha 49) quanto ao default do prop year ser avaliado no nível de módulo.

Important Files Changed

Filename Overview
src/components/InternalComponents/MonthSelectorGrid.vue Adicionado import de Luxon e padronizado o default do prop year para DateTime.now().year. O valor é avaliado em tempo de carregamento do módulo (não por instância), o que pode tornar testes frágeis se o ano mockado diferir do ano real.
src/components/InternalComponents/YearSelectorGrid.vue Adicionado import de Luxon e todayYear passou a usar DateTime.now().year. Por estar dentro do setup(), é avaliado por instância e respeita corretamente o mock de Settings.now nos testes.
src/tests/SelectorGridHighlight.spec.js Adicionado mock de Settings.now do Luxon no beforeEach e limpeza no afterEach. Garante que tanto vi.useFakeTimers quanto DateTime.now() utilizem a data mockada durante os testes.
src/utils/constants/inputTypes.js Adicionado 'date' à lista de tipos válidos de input, eliminando o aviso de validação de prop quando DateInput.vue passa type="date" para BaseInput.vue.
src/components/InlineDateInput.vue Alterado new Date() para DateTime.now().toJSDate() no atributo dates do data(). Padroniza o uso de Luxon e permite que Settings.now funcione como mock nos testes.
package.json Bump de versão: 3.154.11 → 3.154.12 (alteração também refletida no package-lock.json).

Sequence Diagram

sequenceDiagram
    participant TF as Test File
    participant VT as Vitest
    participant LX as Luxon Settings
    participant MC as MonthSelectorGrid
    participant YC as YearSelectorGrid

    TF->>MC: import (módulo carregado)
    Note over MC: DateTime.now().year avaliado<br/>em tempo de módulo (2026)
    TF->>YC: import (módulo carregado)

    loop beforeEach (cada teste)
        TF->>VT: vi.useFakeTimers()
        TF->>VT: vi.setSystemTime(new Date(2026, 1, 10))
        TF->>LX: Settings.now = () => mockDate.getTime()
    end

    TF->>MC: mount(MonthSelectorGrid, props)
    Note over MC: defineProps default já fixado<br/>em 2026 (módulo-level)
    TF->>YC: mount(YearSelectorGrid, props)
    Note over YC: setup() executa → DateTime.now().year<br/>avaliado por instância → responde ao mock

    loop afterEach (cada teste)
        TF->>VT: vi.useRealTimers()
        TF->>LX: Settings.now = () => Date.now()
    end
Loading

Last reviewed commit: 80e146a

year: {
type: Number,
default: new Date().getFullYear(),
default: DateTime.now().year,
Copy link

Choose a reason for hiding this comment

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

Padrão default de prop avaliado em tempo de carregamento do módulo

DateTime.now().year nessa posição (dentro do objeto literal de defineProps) é avaliado uma única vez, quando o módulo é importado, e não por instância do componente. Isso acontece porque o compilador do Vue 3 extrai o objeto de defineProps para o nível de módulo (nas opções do componente), fora da função setup.

Por isso, mocks de Settings.now configurados no beforeEach dos testes não afetam esse valor padrão, pois o módulo já foi importado antes de qualquer beforeEach ser executado. Os testes atuais passam porque o ano mockado (2026) coincide com o ano real — mas isso é frágil.

A variável todayYear em YearSelectorGrid.vue não tem esse problema porque é declarada diretamente no topo do setup() (dentro do corpo da função), sendo avaliada por instância.

Para garantir que o default seja avaliado por instância e respeite mocks em testes, utilize uma factory function:

Suggested change
default: DateTime.now().year,
default: () => DateTime.now().year,

Rule Used: What: Components in Vue 3 must adhere to the speci... (source)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐛 Bug Algo não está funcionando

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants