Files
web/packages/design-system/lib/components/InputNew/utils.test.ts
Rasmus Langvad edca33c49f Merged in feat/SW-3655-input-component (pull request #3296)
feat: (SW-3655) new Input and FormInput components

* First version new Input and FormInput components

* Handle aria-describedby with react-aria instead of manually add it

* Update breaking unit and stories tests

* Merge branch 'master' into feat/SW-3655-input-component

* Update example form

* Merge branch 'master' into feat/SW-3655-input-component

* New lock file


Approved-by: Linus Flood
2025-12-08 08:51:03 +00:00

104 lines
2.6 KiB
TypeScript

import { describe, expect, it, vi, beforeEach } from 'vitest'
import { renderHook } from '@testing-library/react'
import { useInputHasValue, clearInput } from './utils'
describe('useInputHasValue', () => {
const createMockRef = (value = '') => ({
current: { value } as HTMLInputElement,
})
describe('controlled input (value prop)', () => {
it('returns true when value has content', () => {
const ref = createMockRef()
const { result } = renderHook(() => useInputHasValue('hello', ref))
expect(result.current).toBe(true)
})
it('returns false when value is empty string', () => {
const ref = createMockRef()
const { result } = renderHook(() => useInputHasValue('', ref))
expect(result.current).toBe(false)
})
it('returns false when value is only whitespace', () => {
const ref = createMockRef()
const { result } = renderHook(() => useInputHasValue(' ', ref))
expect(result.current).toBe(false)
})
it('updates when value prop changes', () => {
const ref = createMockRef()
const { result, rerender } = renderHook(
({ value }) => useInputHasValue(value, ref),
{ initialProps: { value: '' } }
)
expect(result.current).toBe(false)
rerender({ value: 'new value' })
expect(result.current).toBe(true)
})
})
})
describe('clearInput', () => {
beforeEach(() => {
vi.restoreAllMocks()
})
it('calls onChange with empty value for controlled input', () => {
const onChange = vi.fn()
const inputRef = {
current: {
value: 'test',
focus: vi.fn(),
} as unknown as HTMLInputElement,
}
clearInput({
inputRef,
onChange,
value: 'test',
})
expect(onChange).toHaveBeenCalledWith(
expect.objectContaining({
target: { value: '' },
})
)
expect(inputRef.current.focus).toHaveBeenCalled()
})
it('sets input value directly for uncontrolled input', () => {
const input = document.createElement('input')
input.value = 'test'
const focusSpy = vi.spyOn(input, 'focus')
const dispatchSpy = vi.spyOn(input, 'dispatchEvent')
const inputRef = { current: input }
clearInput({
inputRef,
onChange: undefined,
value: undefined,
})
expect(input.value).toBe('')
expect(dispatchSpy).toHaveBeenCalled()
expect(focusSpy).toHaveBeenCalled()
})
it('does nothing when ref is null', () => {
const onChange = vi.fn()
const inputRef = { current: null }
clearInput({
inputRef,
onChange,
value: 'test',
})
expect(onChange).not.toHaveBeenCalled()
})
})