import React, { useState } from 'react'
import { act, fireEvent, render, screen } from '@toptal/picasso-test-utils'
import type { FormApi } from 'final-form'
import { useForm } from 'react-final-form'
import type { FormConfigProps } from '../FormConfig'
import { FormCompound as Form } from '../FormCompound'
import type { Props as RadioGroupProps } from '../RadioGroup'
const renderFormRadio = (
{ required, name }: RadioGroupProps,
formConfig: FormConfigProps = {}
) =>
render(
)
describe('FormRadio', () => {
it('renders', () => {
const { container } = renderFormRadio({
name: 'color',
})
expect(container).toMatchSnapshot()
})
it('required with asterisk', () => {
const { container } = renderFormRadio(
{
name: 'color',
required: true,
},
{
requiredVariant: 'asterisk',
}
)
expect(container).toMatchSnapshot()
})
describe('with a field of its own', () => {
const Toggleable = ({ children }: { children: React.ReactNode }) => {
const [mounted, setMounted] = useState(true)
return (
<>
{mounted && children}
>
)
}
it('keeps its stored value when it remounts', () => {
const formRef: { current?: FormApi } = {}
const CaptureForm = () => {
formRef.current = useForm()
return null
}
render(
)
act(() => {
formRef.current?.change('size', 'large')
})
fireEvent.click(screen.getByRole('button', { name: 'toggle' }))
fireEvent.click(screen.getByRole('button', { name: 'toggle' }))
expect(screen.getByLabelText('Large')).toBeChecked()
expect(formRef.current?.getState().values.size).toBe('large')
})
it('moves to a field of its own when a new `name` takes it out of its group', () => {
const formRef: { current?: FormApi } = {}
const CaptureForm = () => {
formRef.current = useForm()
return null
}
const renderRadio = (name?: string) => (
)
const { rerender } = render(renderRadio())
rerender(renderRadio('size'))
expect(screen.getByLabelText('Small')).toBeInTheDocument()
expect(formRef.current?.getRegisteredFields()).toContain('size')
})
})
})