Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

9.3 KB
Raw Blame
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import Settings from './Settings'
import { i18n } from '@lyftr/shared'
import { exerciseAPI } from '../services/api'
import { useLanguageStore } from '../lib/lyftr'

// What these pin is the shape of the WRITES this page makes, which is where #170 went
// wrong twice. The name began life inside `formData`, and the only button that commits
// `formData` is labelled "Save targets", sits in another section, and disappears
// entirely when the settings read fails — so the field could not be saved on purpose and
// could be saved by accident, because the weight-unit toggle sent the whole form.
//
// Hence: every assertion below is about which keys reach `update`.

const update = vi.fn()
const fetchSettings = vi.fn()

let state: Record<string, unknown>

const makeState = (over: Record<string, unknown> = {}) => ({
  settings: {
    user_id: 1,
    weight_unit: 'lbs',
    calorie_target: 2000,
    protein_target: 150,
    carb_target: 250,
    fat_target: 65,
    timezone: 'UTC',
    display_name: '',
    workout_layout: 'list',
    rest_enabled: true,
    rest_seconds_default: 90,
  },
  loaded: true,
  loadFailed: false,
  update,
  fetch: fetchSettings,
  setWorkoutLayout: vi.fn(),
  setRestEnabled: vi.fn(),
  setRestSeconds: vi.fn(),
  ...over,
})

vi.mock('../stores/settings', () => ({
  useSettingsStore: Object.assign(
    (selector?: (s: unknown) => unknown) => (selector ? selector(state) : state),
    { getState: () => state },
  ),
}))

vi.mock('../stores/auth', () => ({
  useAuthStore: () => ({
    user: { id: 1, email: '[email protected]', created_at: '2026-07-01T00:00:00Z' },
    logout: vi.fn(),
  }),
}))

vi.mock('../stores/server', () => ({ useServerStore: () => '' }))
vi.mock('../hooks/useServerInfo', () => ({ useServerInfo: () => null }))
vi.mock('../hooks/useTheme', () => ({ useTheme: () => ({ theme: 'dark', toggleTheme: vi.fn() }) }))
vi.mock('../components/ServerSettings', () => ({ default: () => null }))
vi.mock('../services/api', () => ({
  exerciseAPI: {
    cacheStatus: vi.fn().mockResolvedValue({ count: 0 }),
    refreshCache: vi.fn(),
  },
  userAPI: { deleteAccount: vi.fn() },
}))

const renderPage = () => render(<MemoryRouter><Settings /></MemoryRouter>)
const nameField = () => screen.getByLabelText('Name')

beforeEach(() => {
  vi.clearAllMocks()
  state = makeState()
  update.mockResolvedValue(undefined)
})

describe('the Name row', () => {
  it('offers no Save until the name actually changes', async () => {
    renderPage()
    await waitFor(() => expect(nameField()).toBeTruthy())

    expect(screen.queryByRole('button', { name: 'Save' })).toBeNull()

    fireEvent.change(nameField(), { target: { value: 'Carter' } })
    expect(screen.getByRole('button', { name: 'Save' })).toBeTruthy()
  })

  // The regression: it must send ONLY its own field. Sending the whole form is how the
  // unit toggle used to commit a half-typed name.
  it('sends only display_name, trimmed', async () => {
    renderPage()
    await waitFor(() => expect(nameField()).toBeTruthy())

    fireEvent.change(nameField(), { target: { value: '  Carter  ' } })
    fireEvent.click(screen.getByRole('button', { name: 'Save' }))

    await waitFor(() => expect(update).toHaveBeenCalledTimes(1))
    expect(update).toHaveBeenCalledWith({ display_name: 'Carter' })
  })

  // The other half of the same bug, from the other direction.
  it('does not carry a half-typed name when the weight unit is changed', async () => {
    renderPage()
    await waitFor(() => expect(nameField()).toBeTruthy())

    fireEvent.change(nameField(), { target: { value: 'Half' } })
    fireEvent.click(screen.getByRole('button', { name: 'kg' }))

    await waitFor(() => expect(update).toHaveBeenCalledTimes(1))
    expect(update).toHaveBeenCalledWith({ weight_unit: 'kg' })
  })

  // `loadFailed` means the settings on screen are substitutes, not the user's. Offering
  // to write a name over one we failed to read is the silent-default-substitution shape
  // the rest of this page was hardened against.
  it('will not offer to overwrite a name it could not read', async () => {
    state = makeState({ loadFailed: true })
    renderPage()

    await waitFor(() => expect(screen.getByText(/Couldn't load your name/)).toBeTruthy())
    expect(screen.queryByLabelText('Name')).toBeNull()
    expect(screen.queryByRole('button', { name: 'Save' })).toBeNull()
  })

  // The in-flight "Saving…" state is deliberately NOT tested here. It only appears
  // because the real store applies its patch optimistically before awaiting, which makes
  // the row stop being dirty mid-write — and this file's store is a plain stub that never
  // re-renders, so any assertion about it passes whether the fix is present or not. It is
  // verified against the real store in a browser with the response delayed instead.
  it('names the field and its help text for a screen reader', async () => {
    renderPage()
    await waitFor(() => expect(nameField()).toBeTruthy())

    const described = nameField().getAttribute('aria-describedby')
    expect(described).toBeTruthy()
    expect(document.getElementById(described!)?.textContent).toMatch(/use your email/)
  })
})

describe('the exercise library banner', () => {
  afterEach(async () => { await i18n.changeLanguage('en') })

  // The banner is state that outlives the click that raised it. It keeps the key and the
  // failure, not the sentence, so a language switch while it is showing re-words it.
  it('re-renders a visible failure in the new language without a reload (es)', async () => {
    const { exerciseAPI } = await import('../services/api')
    vi.mocked(exerciseAPI.refreshCache).mockRejectedValue({ response: { status: 400, data: { error: '' } } })
    renderPage()

    fireEvent.click(await screen.findByRole('button', { name: 'Refresh cached' }))
    await waitFor(() => expect(screen.getByText("Couldn't refresh the cache.")).toBeTruthy())

    await act(async () => { await i18n.changeLanguage('es') })
    expect(screen.getByText('No se pudo actualizar la caché.')).toBeTruthy()
    expect(screen.queryByText("Couldn't refresh the cache.")).toBeNull()
  })
})

describe('language', () => {
  afterEach(async () => {
    await i18n.changeLanguage('en')
    useLanguageStore.setState({ preference: 'system' })
    localStorage.clear()
  })

  const picker = () => screen.getByRole('combobox', { name: /Language|Idioma/ }) as HTMLSelectElement

  it('lists System first, then languages by their own names', async () => {
    renderPage()
    await waitFor(() => expect(screen.getByRole('heading', { name: 'Settings' })).toBeTruthy())
    const options = Array.from(picker().options)
    expect(options.map(o => o.value)).toEqual(['system', 'en', 'es'])
    expect(options[0].textContent).toBe('System (English)')
    expect(options[1].textContent).toBe('English')
    expect(options[1].getAttribute('translate')).toBe('no')
    expect(options[2].getAttribute('lang')).toBe('es')
    expect(options[2].getAttribute('translate')).toBe('no')
    // The name stays short so the selected value never clips; the marker is said below.
    expect(options[2].textContent).toBe('Español')
  })

  it('switches the whole page live and remembers the choice', async () => {
    renderPage()
    await waitFor(() => expect(screen.getByRole('heading', { name: 'Settings' })).toBeTruthy())

    fireEvent.change(picker(), { target: { value: 'es' } })
    await waitFor(() => expect(screen.getByRole('heading', { name: 'Ajustes' })).toBeTruthy())
    expect(localStorage.getItem('lyftr_language')).toBe('es')
    expect(picker().value).toBe('es')
    expect(picker().getAttribute('aria-label')).toBe('Idioma')

    fireEvent.change(picker(), { target: { value: 'system' } })
    await waitFor(() => expect(screen.getByRole('heading', { name: 'Settings' })).toBeTruthy())
  })
})

describe('the catalog sync lines', () => {
  const cacheStatus = vi.mocked(exerciseAPI.cacheStatus)
  const base = { count: 5, syncing: false, last_synced_at: null, last_attempt_at: null, next_attempt_at: null, last_failed: false, last_failure: null }

  it('says Syncing while a pass runs', async () => {
    cacheStatus.mockResolvedValueOnce({ ...base, syncing: true })
    renderPage()
    expect(await screen.findByText('Syncing…')).toBeTruthy()
  })

  it('names an unreachable catalog and when it tries again', async () => {
    cacheStatus.mockResolvedValueOnce({
      ...base, last_failed: true, last_failure: 'unreachable',
      next_attempt_at: new Date(Date.now() + 30 * 60e3).toISOString(),
    })
    renderPage()
    expect(await screen.findByText(/Last sync couldn't reach the exercise catalog\. Trying again at /)).toBeTruthy()
  })

  it('shows no sync line for a server that sends only the count', async () => {
    cacheStatus.mockResolvedValueOnce({ count: 0 })
    renderPage()
    await waitFor(() => expect(cacheStatus).toHaveBeenCalled())
    expect(screen.queryByText(/Last synced/)).toBeNull()
  })

  it('reloads the status after a refresh that failed', async () => {
    vi.mocked(exerciseAPI.refreshCache).mockRejectedValueOnce(new Error('503'))
    renderPage()
    await waitFor(() => expect(cacheStatus).toHaveBeenCalledTimes(1))
    fireEvent.click(screen.getByRole('button', { name: 'Refresh cached' }))
    await waitFor(() => expect(cacheStatus).toHaveBeenCalledTimes(2))
  })
})