Skip to content

Commit

Permalink
Add tests around use of custom components with UseField
Browse files Browse the repository at this point in the history
There was an issue previously where memoized components would not work;
these are primarily regression tests covering that use case.
  • Loading branch information
rylnd committed Sep 10, 2020
1 parent 5094b04 commit a9a6703
Showing 1 changed file with 61 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
import React, { useEffect } from 'react';
import React, { useEffect, FunctionComponent } from 'react';
import { act } from 'react-dom/test-utils';

import { registerTestBed, TestBed } from '../shared_imports';
Expand Down Expand Up @@ -237,4 +237,64 @@ describe('<UseField />', () => {
expect(serializer).not.toBeCalled();
});
});

describe('custom components', () => {
interface MyForm {
name: string;
}

let formHook: FormHook<MyForm> | null = null;

beforeEach(() => {
formHook = null;
});

const onFormHook = (_form: FormHook<MyForm>) => {
formHook = _form;
};

const TestComp = ({
component,
onForm,
}: {
component: FunctionComponent<any>;
onForm: (form: FormHook<MyForm>) => void;
}) => {
const { form } = useForm<MyForm>();

useEffect(() => {
onForm(form);
}, [onForm, form]);

return (
<Form form={form}>
<UseField path="name" defaultValue="myName" component={component} />
</Form>
);
};

it('allows function components', () => {
const Component = () => <textarea data-test-subj="function-component" />;
const setup = registerTestBed(TestComp, {
defaultProps: { onForm: onFormHook, component: Component },
memoryRouter: { wrapComponent: false },
});
const testBed = setup() as TestBed;

expect(testBed.exists('function-component')).toEqual(true);
expect(formHook?.getFormData()).toEqual({ name: 'myName' });
});

it('allows memoized function components', () => {
const Component = React.memo(() => <textarea data-test-subj="memoized-component" />);
const setup = registerTestBed(TestComp, {
defaultProps: { onForm: onFormHook, component: Component },
memoryRouter: { wrapComponent: false },
});
const testBed = setup() as TestBed;

expect(testBed.exists('memoized-component')).toEqual(true);
expect(formHook?.getFormData()).toEqual({ name: 'myName' });
});
});
});

0 comments on commit a9a6703

Please sign in to comment.