/* eslint-disable max-lines-per-function */ import React, { Suspense, useState } from 'react' import { act, fireEvent, render, screen } from '@toptal/picasso-test-utils' 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 type { FieldArrayRenderProps } from './index' import { FieldArray, useFieldArray } from './index' interface Skill { name: string } const initialValues = { skills: [{ name: 'HTML' }, { name: 'CSS' }] } // For an array the form holds nothing for const languages = [{ name: 'Croatian' }] const renderForm = (children: React.ReactNode) => render(
{children}
) const SkillList = ({ fields, }: Pick, 'fields'>) => ( ) const getSkills = () => screen.getAllByRole('listitem').map(item => item.textContent) const PushButton = ({ fields, }: Pick, 'fields'>) => ( ) const PopButton = ({ fields, }: Pick, 'fields'>) => ( ) const Toggleable = ({ children }: { children: React.ReactNode }) => { const [mounted, setMounted] = useState(true) return ( <> {mounted && children} ) } const FirstValue = ({ value }: { value: unknown }) => { const [first] = useState(value) return {String(first)} } // Reads the array without an `initialValue`, so the form keeps its entry with // nothing stored const Reader = () => { const { fields } = useFieldArray('languages') return {`read ${fields.length ?? 0}`} } // A wizard step reading the array gives way to the one seeding it, in the same // commit const Steps = ({ children }: { children: React.ReactNode }) => { const [step, setStep] = useState(1) return ( <> {step === 1 ? : children} ) } // Seeds the array with its own `initialValue` and shows how many items its // first render had const SeededLanguages = () => { const { fields } = useFieldArray('languages', { initialValue: languages, }) return } // Mounts its children on a click, next to fields that stay mounted const Later = ({ children }: { children: React.ReactNode }) => { const [shown, setShown] = useState(false) return ( <> {shown && children} ) } const pushAndRemount = () => { fireEvent.click(screen.getByRole('button', { name: 'push' })) fireEvent.click(screen.getByRole('button', { name: 'toggle' })) fireEvent.click(screen.getByRole('button', { name: 'toggle' })) } // Stores an array equal to the initial one item by item, but a new array const pushPopAndRemount = () => { fireEvent.click(screen.getByRole('button', { name: 'push' })) fireEvent.click(screen.getByRole('button', { name: 'pop' })) fireEvent.click(screen.getByRole('button', { name: 'toggle' })) fireEvent.click(screen.getByRole('button', { name: 'toggle' })) } describe('FieldArray', () => { it('renders the items through a function child', () => { renderForm( name='skills'> {({ fields }) => } ) expect(getSkills()).toEqual(['HTML', 'CSS']) }) it('renders the items through the component prop', () => { renderForm( name='skills' component={SkillList} />) expect(getSkills()).toEqual(['HTML', 'CSS']) }) it('exposes the final-form-arrays mutators, `update` included', () => { renderForm( name='skills'> {({ fields }) => ( <> )} ) fireEvent.click(screen.getByRole('button', { name: 'push' })) fireEvent.click(screen.getByRole('button', { name: 'update' })) fireEvent.click(screen.getByRole('button', { name: 'remove' })) expect(getSkills()).toEqual(['HTML5', 'JavaScript']) }) it("subscribes to upstream's default keys only, so other meta reads undefined", () => { renderForm( name='skills'> {({ meta }) => {`pristine: ${String(meta.pristine)}`}} ) expect(screen.getByText('pristine: undefined')).toBeInTheDocument() }) it('widens the meta to an explicit subscription', () => { renderForm( name='skills' subscription={{ pristine: true }}> {({ meta }) => {`pristine: ${String(meta.pristine)}`}} ) expect(screen.getByText('pristine: true')).toBeInTheDocument() }) it('keeps the items the user added when it remounts', () => { renderForm( name='skills'> {({ fields }) => ( <> )} ) pushAndRemount() expect(getSkills()).toEqual(['HTML', 'CSS', 'JavaScript']) }) it('renders its initial items on its first render', () => { renderForm( name='skills'> {({ fields }) => } ) expect(screen.getByRole('status')).toHaveTextContent('2') }) it.each(['initialValue', 'defaultValue'] as const)( 'renders the items of its own `%s` on its first render', seed => { renderForm( name='languages' {...{ [seed]: languages }}> {({ fields }) => } ) expect(screen.getByRole('status')).toHaveTextContent('1') } ) it.each(['initialValue', 'defaultValue'] as const)( 'renders the items of its own `%s` on its first render after a step that reads the array', seed => { renderForm( name='languages' {...{ [seed]: languages }}> {({ fields }) => } ) fireEvent.click(screen.getByRole('button', { name: 'next' })) expect(screen.getByRole('status')).toHaveTextContent('1') } ) it('renders the stored items on its first render after a remount', () => { renderForm( name='skills'> {({ fields }) => ( <> )} ) pushAndRemount() expect(screen.getByRole('status')).toHaveTextContent('3') }) it('reports equal items as pristine on its first render after a remount', () => { renderForm( name='skills' subscription={{ pristine: true }}> {({ fields, meta }) => ( <> )} ) pushPopAndRemount() expect(screen.getByRole('status')).toHaveTextContent('true') }) describe('useFieldArray', () => { it('returns the fields of the named array, typed by the item', () => { const Skills = () => { const { fields } = useFieldArray('skills') const names = fields.value.map(skill => skill.name).join(', ') return {`${names} (${fields.length})`} } renderForm() expect(screen.getByText('HTML, CSS (2)')).toBeInTheDocument() }) it('keeps the items the user added when the array remounts', () => { const Skills = () => { const { fields } = useFieldArray('skills') return ( <> ) } renderForm( ) pushAndRemount() expect(getSkills()).toEqual(['HTML', 'CSS', 'JavaScript']) }) it('renders the initial items on the first render', () => { const Skills = () => { const { fields } = useFieldArray('skills') return } renderForm() expect(screen.getByRole('status')).toHaveTextContent('2') }) it('renders the items of its own `initialValue` on the first render', () => { const Languages = () => { const { fields } = useFieldArray('languages', { initialValue: languages, }) return } renderForm() expect(screen.getByRole('status')).toHaveTextContent('1') }) it('renders the items of its own `initialValue` on the first render after a step that reads the array', () => { renderForm( ) fireEvent.click(screen.getByRole('button', { name: 'next' })) expect(screen.getByRole('status')).toHaveTextContent('1') }) it('renders the items of its own `initialValue` on the first render next to a hook that reads the array', () => { renderForm( <> ) fireEvent.click(screen.getByRole('button', { name: 'show' })) expect(screen.getByRole('status')).toHaveTextContent('1') expect(screen.getByText('read 1')).toBeInTheDocument() }) it('leaves nothing registered after a reset empties the array a suspended first render seeded next to a reader', async () => { jest.useFakeTimers() const formRef: { current?: FormApi } = {} const CaptureForm = () => { formRef.current = useForm() return null } let suspending = true let resume = () => {} const resumed = new Promise(resolve => { resume = resolve }) const Suspending = () => { if (suspending) { throw resumed } return null } try { const { unmount } = renderForm( <> ) // The seeded render suspends, so its hold waits for the timeout fireEvent.click(screen.getByRole('button', { name: 'show' })) act(() => formRef.current?.initialize({})) // The retry seeds the emptied array again await act(async () => { suspending = false resume() await resumed }) expect(screen.getByRole('status')).toHaveTextContent('1') unmount() jest.runOnlyPendingTimers() expect(formRef.current?.getRegisteredFields()).not.toContain( 'languages' ) } finally { jest.useRealTimers() } }) it('leaves an array the form drops after the first render empty', () => { const Languages = () => { const form = useForm() const { fields } = useFieldArray('languages', { initialValue: languages, }) return ( <> {`languages ${fields.length}`} ) } renderForm() fireEvent.click(screen.getByRole('button', { name: 'drop' })) expect(screen.getByText('languages 0')).toBeInTheDocument() }) it('renders the stored items on the first render after a remount', () => { const Skills = () => { const { fields } = useFieldArray('skills') return ( <> ) } renderForm( ) pushAndRemount() expect(screen.getByRole('status')).toHaveTextContent('3') }) it('reports equal items as pristine on the first render after a remount', () => { const Skills = () => { const { fields, meta } = useFieldArray('skills', { subscription: { pristine: true }, }) return ( <> ) } renderForm( ) pushPopAndRemount() expect(screen.getByRole('status')).toHaveTextContent('true') }) }) })