From 5f85cbac57b17a5cfab54f2e1254a6f9c8eb2f70 Mon Sep 17 00:00:00 2001 From: Anton Dosov Date: Wed, 14 Sep 2022 13:34:52 +0200 Subject: [PATCH] add a unit test --- .../hook_form_lib/hooks/use_field.test.tsx | 86 +++++++++++++++---- 1 file changed, 69 insertions(+), 17 deletions(-) diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_field.test.tsx b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_field.test.tsx index c5e24a578bd86..98050a81ade9a 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_field.test.tsx +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_field.test.tsx @@ -16,8 +16,6 @@ import { emptyField } from '../../helpers/field_validators'; import { FieldHook, FieldValidateResponse, VALIDATION_TYPES, FieldConfig } from '..'; describe('useField() hook', () => { - let fieldHook: FieldHook; - beforeAll(() => { jest.useFakeTimers(); }); @@ -26,22 +24,23 @@ describe('useField() hook', () => { jest.useRealTimers(); }); - const TestField = ({ field }: { field: FieldHook }) => { - fieldHook = field; - return null; - }; - - const getTestForm = (config?: FieldConfig) => () => { - const { form } = useForm(); - - return ( -
- - - ); - }; - describe('field.validate()', () => { + let fieldHook: FieldHook; + const TestField = ({ field }: { field: FieldHook }) => { + fieldHook = field; + return null; + }; + + const getTestForm = (config?: FieldConfig) => () => { + const { form } = useForm(); + + return ( +
+ + + ); + }; + const EMPTY_VALUE = ' '; test('it should not invalidate a field with arrayItem validation when isBlocking is false', async () => { @@ -149,4 +148,57 @@ describe('useField() hook', () => { expect(validatorFn).toBeCalledTimes(0); }); }); + + describe('fieldsToValidateOnChange', () => { + let fieldHook1: FieldHook; + let fieldHook2: FieldHook; + const TestField1 = ({ field }: { field: FieldHook }) => { + fieldHook1 = field; + return null; + }; + + const TestField2 = ({ field }: { field: FieldHook }) => { + fieldHook2 = field; + return null; + }; + + const getTestForm = + (configField1?: FieldConfig, configField2?: FieldConfig) => + ({ showField1, showField2 }: { showField1: boolean; showField2: boolean }) => { + const { form } = useForm(); + + return ( +
+ {showField1 && } + {showField2 && } + + ); + }; + + test('validates dependent fields on unmount', async () => { + const field2ValidatorFn = jest.fn(); + const TestForm = getTestForm( + { + fieldsToValidateOnChange: ['field1', 'field2'], + }, + { + validations: [ + { + validator: field2ValidatorFn, + }, + ], + } + ); + + const wrapper = registerTestBed(TestForm, { + memoryRouter: { wrapComponent: false }, + })({ showField1: true, showField2: true }); + expect(field2ValidatorFn).toBeCalledTimes(0); + + await act(async () => { + wrapper.setProps({ showField1: false }); + }); + expect(field2ValidatorFn).toBeCalledTimes(1); + }); + }); });