|
| 1 | +import { fireEvent, render } from '@testing-library/react'; |
| 2 | +import React, { useState } from 'react'; |
| 3 | +import Form, { Field, type FormInstance } from '../src'; |
| 4 | +import { changeValue, getInput } from './common'; |
| 5 | +import { Input } from './common/InfoField'; |
| 6 | + |
| 7 | +describe('Form.clearOnDestroy', () => { |
| 8 | + it('works', async () => { |
| 9 | + let formCache: FormInstance | undefined; |
| 10 | + const Demo = ({ load }: { load?: boolean }) => { |
| 11 | + const [form] = Form.useForm(); |
| 12 | + formCache = form; |
| 13 | + |
| 14 | + return ( |
| 15 | + <> |
| 16 | + {load && ( |
| 17 | + <Form form={form} initialValues={{ count: '1' }} clearOnDestroy> |
| 18 | + <Field name="count"> |
| 19 | + <Input /> |
| 20 | + </Field> |
| 21 | + </Form> |
| 22 | + )} |
| 23 | + </> |
| 24 | + ); |
| 25 | + }; |
| 26 | + const { rerender } = render(<Demo load />); |
| 27 | + expect(formCache.getFieldsValue(true)).toEqual({ count: '1' }); |
| 28 | + rerender(<Demo />); |
| 29 | + expect(formCache.getFieldsValue(true)).toEqual({}); |
| 30 | + |
| 31 | + // Rerender back should filled again |
| 32 | + rerender(<Demo load />); |
| 33 | + expect(formCache.getFieldsValue(true)).toEqual({ count: '1' }); |
| 34 | + }); |
| 35 | + |
| 36 | + it('change value', async () => { |
| 37 | + let formCache: FormInstance | undefined; |
| 38 | + const Demo = () => { |
| 39 | + const [load, setLoad] = useState(true); |
| 40 | + |
| 41 | + const [form] = Form.useForm(); |
| 42 | + formCache = form; |
| 43 | + |
| 44 | + return ( |
| 45 | + <> |
| 46 | + <button onClick={() => setLoad(c => !c)}>load</button> |
| 47 | + {load && ( |
| 48 | + <Form form={form} clearOnDestroy> |
| 49 | + <Field name="count"> |
| 50 | + <Input /> |
| 51 | + </Field> |
| 52 | + </Form> |
| 53 | + )} |
| 54 | + </> |
| 55 | + ); |
| 56 | + }; |
| 57 | + const { container, queryByText } = render(<Demo />); |
| 58 | + await changeValue(getInput(container), 'bamboo'); |
| 59 | + expect(formCache.getFieldsValue(true)).toEqual({ count: 'bamboo' }); |
| 60 | + fireEvent.click(queryByText('load')); |
| 61 | + expect(formCache.getFieldsValue(true)).toEqual({}); |
| 62 | + formCache.setFields([{ name: 'count', value: '1' }]); |
| 63 | + expect(formCache.getFieldsValue(true)).toEqual({ count: '1' }); |
| 64 | + }); |
| 65 | +}); |
0 commit comments