sonda/web/src/components/VolumeControl.test.tsx
tgiachi 606845ae72 feat(web): a volume control with a mute button and a slider
The slider shows zero while muted and moving it unmutes; on a phone the slider is hidden, since the device has its own volume, and the button stays.
2026-11-12 15:22:57 +01:00

61 lines
2.5 KiB
TypeScript

import { act, fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, expect, test, vi } from 'vitest'
import { initI18n } from '@/i18n'
import { usePlayer } from '@/player/store'
import VolumeControl from './VolumeControl'
beforeEach(async () => {
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
await initI18n()
localStorage.clear()
usePlayer.setState({ volume: 0.5, muted: false })
})
const slider = () => screen.getByRole('slider', { name: 'Volume' })
test('it has a mute button and a slider that shows the level in percent', () => {
render(<VolumeControl />)
expect(screen.getByRole('button', { name: 'Mute' })).toBeInTheDocument()
expect(slider()).toHaveValue('50')
expect(slider()).toHaveAttribute('aria-valuetext', '50%')
expect(slider()).toHaveAttribute('min', '0')
expect(slider()).toHaveAttribute('max', '100')
})
test('moving the slider sets the volume', () => {
render(<VolumeControl />)
fireEvent.change(slider(), { target: { value: '30' } })
expect(usePlayer.getState().volume).toBe(0.3)
})
test('the slider follows the volume when it is changed elsewhere', () => {
render(<VolumeControl />)
act(() => usePlayer.getState().setVolume(0.8))
expect(slider()).toHaveValue('80')
})
test('the mute button mutes, says so, and the slider falls to zero without losing the level', async () => {
render(<VolumeControl />)
await userEvent.click(screen.getByRole('button', { name: 'Mute' }))
expect(usePlayer.getState()).toMatchObject({ muted: true, volume: 0.5 })
expect(screen.getByRole('button', { name: 'Unmute' })).toBeInTheDocument()
expect(slider()).toHaveValue('0')
expect(slider()).toHaveAttribute('aria-valuetext', '0%')
await userEvent.click(screen.getByRole('button', { name: 'Unmute' }))
expect(usePlayer.getState()).toMatchObject({ muted: false, volume: 0.5 })
expect(slider()).toHaveValue('50')
})
test('moving the slider while muted unmutes', () => {
usePlayer.setState({ muted: true })
render(<VolumeControl />)
fireEvent.change(slider(), { target: { value: '70' } })
expect(usePlayer.getState()).toMatchObject({ muted: false, volume: 0.7 })
})
test('on a phone the slider is hidden, since the device has its own volume, and the button stays', () => {
render(<VolumeControl />)
expect(slider().className).toContain('max-sm:hidden')
expect(screen.getByRole('button', { name: 'Mute' }).className).not.toContain('max-sm:hidden')
})