import React, { useState } from 'react' import { act, fireEvent, render, screen } from '@toptal/picasso-test-utils' import { Button } from '@toptal/picasso-button' import type { FormApi } from 'final-form' import arrayMutators from 'final-form-arrays' import { useForm } from 'react-final-form' import { FormCompound as Form } from '../FormCompound' import { FieldArray } from '../FieldArray' import { scrollTo } from '../utils/scroll-to' jest.mock('../utils/scroll-to', () => ({ scrollTo: jest.fn() })) type FormProps = React.ComponentProps const renderForm = ( ui: React.ReactNode, props: Omit, 'onSubmit'> = {} ) => { const handleSubmit = jest.fn() const formRef: { current?: FormApi } = {} const CaptureForm = () => { formRef.current = useForm() return null } render(
{ui} ) return { handleSubmit, getForm: () => formRef.current, submit: () => act(async () => { fireEvent.click(screen.getByText('submit')) }), } } const ToggleableInput = ({ name, required, }: { name: string required?: boolean }) => { const [mounted, setMounted] = useState(true) return ( <> {mounted && ( )} ) } const toggle = () => { fireEvent.click(screen.getByText('toggle')) } const editField = (value: string) => { fireEvent.change(screen.getByPlaceholderText('field'), { target: { value } }) } const ToggleableChildren = ({ children }: { children: React.ReactNode }) => { const [mounted, setMounted] = useState(true) return ( <> {mounted && children} ) } const SeededLater = () => { const [mounted, setMounted] = useState(false) return (
{({ form }) => ( <> {mounted && } )} ) } describe('Field', () => { describe('when a field unmounts and remounts', () => { it('keeps the value the user edited', () => { renderForm(, { initialValues: { a: 'x' } }) editField('y') toggle() toggle() expect(screen.getByPlaceholderText('field')).toHaveValue('y') }) }) describe('when a field mounts over a value the form was already given', () => { it('keeps the seeded value instead of the initial one', () => { render() fireEvent.click(screen.getByText('seed')) expect(screen.getByPlaceholderText('field')).toHaveValue('') }) }) describe('when the form sets `destroyOnUnregister`', () => { it('drops the value on unmount, as final-form does without the workaround', () => { const { getForm } = renderForm(, { destroyOnUnregister: true, initialValues: { a: 'x' }, }) editField('y') toggle() expect(getForm()?.getState().values.a).toBeUndefined() }) }) describe('when a radio or checkbox group remounts', () => { it('keeps the radio the user selected in a group', () => { const { getForm } = renderForm( , { initialValues: { r: 'a' } } ) fireEvent.click(screen.getByLabelText('B')) toggle() toggle() expect(getForm()?.getState().values.r).toBe('b') expect(screen.getByLabelText('B')).toBeChecked() }) it('keeps the checkbox the user toggled in a group', () => { const { getForm } = renderForm( , { initialValues: { c: ['x'] } } ) fireEvent.click(screen.getByLabelText('Y')) toggle() toggle() expect(getForm()?.getState().values.c).toEqual(['x', 'y']) }) }) describe('when a FieldArray drops an item', () => { it('shifts the remaining positional values instead of restoring a stale one', () => { renderForm( name='items'> {({ fields }) => ( <> {fields.map((fieldName, index) => ( ))} )} , { mutators: { ...arrayMutators }, initialValues: { items: [{ label: 'one' }, { label: 'two' }] }, } ) expect(screen.getByPlaceholderText('item-0')).toHaveValue('one') expect(screen.getByPlaceholderText('item-1')).toHaveValue('two') fireEvent.click(screen.getByText('remove first')) expect(screen.getByPlaceholderText('item-0')).toHaveValue('two') expect(screen.queryByPlaceholderText('item-1')).not.toBeInTheDocument() }) }) describe('after a field unmounts', () => { it('still lets a form-level error on the unmounted field block submit', async () => { const { handleSubmit, submit } = renderForm( , { initialValues: { a: 'x' }, validate: values => (values.a === 'y' ? { a: 'not y' } : {}), } ) editField('y') toggle() await submit() expect(handleSubmit).not.toHaveBeenCalled() expect(scrollTo).not.toHaveBeenCalled() }) it('leaves `getRegisteredFields` as final-form reports it', () => { const { getForm } = renderForm(, { initialValues: { a: 'x' }, }) toggle() expect(getForm()?.getRegisteredFields()).not.toContain('a') }) it('does not let a hidden required field block submit', async () => { const { handleSubmit, submit } = renderForm( ) toggle() await submit() expect(handleSubmit).toHaveBeenCalled() }) }) describe('the field configuration final-form only applies once', () => { it('formats a `formatOnBlur` field that was never focused', async () => { const { handleSubmit, submit } = renderForm( Number(value).toFixed(2)} placeholder='amount' />, { initialValues: { amount: '5.0' } } ) await submit() expect(handleSubmit).toHaveBeenCalledWith( { amount: '5.00' }, expect.anything(), expect.anything() ) }) it('formats a `formatOnBlur` field of a radio group', async () => { const { handleSubmit, submit } = renderForm( String(value).toUpperCase()} > , { initialValues: { r: 'a' } } ) await submit() expect(handleSubmit).toHaveBeenCalledWith( { r: 'A' }, expect.anything(), expect.anything() ) }) it("runs the field's `afterSubmit`", async () => { const handleAfterSubmit = jest.fn() const { submit } = renderForm( , { initialValues: { a: 'x' } } ) await submit() expect(handleAfterSubmit).toHaveBeenCalled() }) it("lets the field's `beforeSubmit` block the submit", async () => { const { handleSubmit, submit } = renderForm( false} placeholder='field' />, { initialValues: { a: 'x' } } ) await submit() expect(handleSubmit).not.toHaveBeenCalled() }) it("passes the field's `data` to its state", () => { const { getForm } = renderForm( , { initialValues: { a: 'x' } } ) expect(getForm()?.getFieldState('a')?.data).toEqual( expect.objectContaining({ tag: 'from-props' }) ) }) }) })